C# 使用file.move重命名文件,但为每个新文本添加字符串

C# 使用file.move重命名文件,但为每个新文本添加字符串,c#,C#,这里是初学者 我需要使用(重命名)file.move方法将GetLastWriteTime字符串添加到我的文件名中。如何使用file.move添加字符串 我查了一些类似的信息,得到了我需要的部分答案System.IO.File.Move(“旧文件名”、“新文件名”)是我需要帮助的代码。我尝试向newfilename添加字符串,但它只支持目录 string[] files = Directory.GetFiles("C:/foto's", "*", SearchOption.TopDirector

这里是初学者

我需要使用(重命名)file.move方法将GetLastWriteTime字符串添加到我的文件名中。如何使用file.move添加字符串

我查了一些类似的信息,得到了我需要的部分答案<代码>System.IO.File.Move(“旧文件名”、“新文件名”)是我需要帮助的代码。我尝试向newfilename添加字符串,但它只支持目录

string[] files = Directory.GetFiles("C:/foto's", "*", SearchOption.TopDirectoryOnly);

string filename = Path.GetFileName(photo);

DateTime fileCreatedDate = System.IO.File.GetLastWriteTime(filename);

System.IO.File.Move(@"C:\foto's", @"C:\foto's" + fileCreatedDate);

预期错误,无法在目录位置接受字符串。

我一直倾向于使用FileInfo对象处理此类内容,因为它们内置了日期,具有MoveTo,而不是使用静态文件。Move等

  FileInfo[] fis = new DirectoryInfo(@"C:\foto's").GetFiles("*", SearchOption.TopDirectoryOnly);

  foreach(FileInfo fi in fis){

    //format a string representing the last write time, that is safe for filenames
    string datePart = fi.LastWriteTimeUtc.ToString("_yyyy-MM-dd HH;mm;ss"); //use ; for time because : is not allowed in path

    //break the name into parts based on the .
    string[] nameParts = fi.Name.Split('.');

    //add the date to the last-but-one part of the name
    if(nameParts.Length == 1) //there is no extension on the file
      nameParts[0] += datePart;
    else
      nameParts[nameParts.Length-1] += datePart;

    //join the name back together
    string newName = string.Join(".", nameParts);

    //move the file to the same directory but with a new name. Use Path.Combine to join directory and new file name into a full path
    fi.MoveTo(Path.Combine(fi.DirectoryName, newName));

  }

  Directory.Move(@"c:\foto's", @"c:\photos"); //fix two typos in your directory name ;)

您正在使用fileCreatedDate的默认格式,该格式包含文件路径中非法的字符(特别是“:”)。您应该尝试将其显式格式化为合法格式,例如
fileCreatedDate.ToString(“yyyyMMdd HHmmss”)