首页 > 解决方案 > 附加时间戳并移动文件 C#

问题描述

我正在尝试通过以下方式将时间戳附加到名称来移动和重命名文件:

private void MoveFile(string from, string to, string filename) {

    File.Move(from, System.IO.Path.Combine(to, filename + DateTime.Now.ToString().Replace(":", "-")));
}

我这样称呼它:

MoveFile(currentPath, outputFolderPath, System.IO.Path.GetFileName(currentPath));

这会导致以下异常:

抛出异常:mscoorlib.dll 中的“System.IO.DirectoryNotFoundException”。

如果我删除时间戳的附加,它会起作用。为什么我会收到此错误?

标签: c#system.io.file

解决方案


如果你像这样使用你的函数:

MoveFile(@"C:\Users\Admin\Desktop\IMG_5628.png", @"C:\Users\Admin\Desktop", "IMG_5628.png");

那么您的路径将如下所示:

C:\Users\Admin\Desktop\IMG_5628.png30.09.2019 2-33-34

改变你的功能如下:

    MoveFile(@"C:\Users\Admin\Desktop\IMG_5628.png", @"C:\Users\Admin\Desktop", "IMG_5628.png");

    private void MoveFile(string from, string to, string filename)
    {
        File.Move(from, System.IO.Path.Combine(to, System.IO.Path.GetFileNameWithoutExtension(filename) + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + System.IO.Path.GetExtension(filename)));
    }

并且您的文件的路径将是有效的。

C:\Users\Admin\Desktop\IMG_56282019-30-9--02-39-03.png

推荐阅读