写入文件名中包含特定日期和时间的文本文件

Writing to text file with specific date and time in the file name

我正在尝试将我的所有数据写入一个文本文件,除非我在文件名中添加 DateTime,否则它可以正常工作。
当前代码如下所示:

string time = DateTime.Now.ToString("d");
string name = "MyName";
File.WriteAllText(time+name+"test.txt","HelloWorld");

我遇到了这个异常:

An unhandled exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll

但据我所知,File.WriteAllText() 方法应该创建一个新文件或覆盖已经存在的文件。

有什么建议吗?

替换

string time = DateTime.Now.ToString("d");
File.WriteAllText(time+name+"test.txt","HelloWorld");

string time = DateTime.Now.ToString("yyyyMMdd_HHmmss"); // clean, contains time and sortable
File.WriteAllText(@"C:\yourpath\" + time+name + "test.txt","HelloWorld");

您必须指定整个路径 - 而不仅仅是文件名

根据 MSDNDateTime.Now.ToString("d") 看起来像这样:6/15/2008(编辑:根据您当地的文化,它可能产生有效的文件名)

文件名中的斜杠无效。

这是因为您的名字将解析为“7/29/2015MyNametest.txt”或包含无效字符的其他内容,具体取决于您机器的文化。我给出的示例显然不是有效的文件路径。我们必须删除斜杠 (/)。 Windows.

的文件名中不允许使用它们

请参阅 this 问题作为关于 Windows 和 Linux 的综合文件命名指南。

您可能想要确保路径有效并且日期时间字符串不包含无效字符:

string time = DateTime.Now.ToString("yyyy-MM-dd"); 

  // specify your path here or leave this blank if you just use 'bin' folder
string path = String.Format(@"C:\{0}\YourFolderName\", time);

string filename = "test.txt"; 

// This checks that path is valid, directory exists and if not - creates one:
if(!string.IsNullOrWhiteSpace(path) && !Directory.Exist(path)) 
{
   Directory.Create(path);
}

最后将数据写入文件:

File.WriteAllText(path + filename,"HelloWorld");