繁体   English   中英

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

[英]Renaming a file using file.move, but adding a string for every new text

初学者在这里。

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

我查找了一些类似的信息,并得到了我需要的部分答案。 System.IO.File.Move("oldfilename", "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 而不是使用 static File.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 ;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM