你至少应该包括异常堆栈跟踪,但我猜它在File.Move()
因为DateTime.Now.ToString()
会(根据当前区域性)返回是这样的:
09/04/2014 14:12:00
Obvisouly它不是一个有效的文件名(因为/是路径separa tor所以你会有一些意想不到的事情,并且:是音量分离器,那么它在那里是无效的,并且你得到“给定路径的格式不被支持”)。
你可能做的是:
var now = DateTime.Now;
var newName = String.Format("{0}.{1:0000}{2:00}{3:00}-{4:00}{5:00}{6:00}",
oldName,
now.Year, now.Month, now.Day,
now.Hour, now.Minute, now.Second);
System.IO.File.Move(oldname, newName);
同时请注意,这将增加时间戳文件名,以便test.txt
将成为(与建议代码)类似test.txt-20140904-141200
。如果你想保留的文件扩展名(更名),你可以这样做:
string path = Path.GetDirectoryName(oldName);
string name = Path.GetFileNameWithoutExtension(oldName);
string extension = Path.GetExtensions(oldName);
var now = DateTime.Now;
var newName = String.Format("{0} ({1:0000}{2:00}{3:00}-{4:00}{5:00}{6:00})",
name,
now.Year, now.Month, now.Day,
now.Hour, now.Minute, now.Second);
System.IO.File.Move(oldname,
System.IO.Path.Combine(path, newName + extension));
有了这个代码test.txt
将成为test (20140904-141200).txt
。
看看'DateTime.Now.ToString()';) – Xaruth 2014-09-04 12:20:05