我试图让我的程序复制一个文件并使用它的当前名称和当前日期重命名。这是我目前的代码,我知道它不起作用,但至少它显示了我想要做的事情。我在File.Copy...
说出错了
An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll
var DAT = DateTime.Today;
string DATE = Convert.ToString(DAT);
File.Copy("D:/folder/file.json", "D:/folder/file" + DATE + ".json");
答案 0 :(得分:1)
也许不是最好的解决方案,但它确实有效。
string DAT = Convert.ToString(DateTime.Today);
StringBuilder sb = new StringBuilder(DAT);
sb.Replace(" ", "_");
sb.Replace(":", "_");
var DATE = sb.ToString();
File.Copy("D:/folder/file.json", "D:/folder/file" + DATE + ".json");
你也可以用
替换stringbuilder和String DAT...
string DATE = DateTime.Today.ToString("yyyy-MM-dd");.
答案 1 :(得分:1)
您可以从Path.GetInvalidFileNameChars()和Path.GetInvalidPathChars()
获取所有无效字符,从而替换所有无效字符public static class PathExt
{
public static String ReplaceInvalidChars(String path, Char replacement = '_')
{
if (String.IsNullOrEmpty(path))
throw new ArgumentException(paramName: nameof(path), message: "Empty or null path");
var invalidChars = new HashSet<Char>(Path
.GetInvalidFileNameChars()
.Concat(Path.GetInvalidPathChars()));
return new String(path
.Select(ch =>
invalidChars.Contains(ch) ?
replacement : ch)
.ToArray());
}
}
...
var dateTime = DateTime.Now.ToString();
var dateTimePath = PathExt.ReplaceInvalidChars(dateTime);
Console.WriteLine($"The time is {dateTime}");
Console.WriteLine($"The file is {dateTimePath}");
using (File.Create(dateTimePath))
{
Console.WriteLine("File created");
}