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



这里是初级程序员。

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

我查了一些类似的信息,得到了我需要的部分答案。System.IO.File.Move("oldfilename", "newfilename");是我需要帮助的代码。我尝试在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,而不是使用静态文件。移动etc。。。

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 ;)

最新更新