写入文件名中带有特定日期和时间的文本文件

本文关键字:日期 时间 文件 文本 文件名 | 更新日期: 2023-09-27 18:05:12

我正试图将所有数据写入文本文件,除非我将DateTime放在文件名中,否则它正在工作。
当前代码如下所示:

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

我得到了这个异常:

未处理的System.IO类型异常。目录notfoundexception '发生在mscorlib.dll

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

有什么建议吗?

写入文件名中带有特定日期和时间的文本文件

您可能想要确保路径是有效的,并且datetime字符串不包含无效字符:

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

根据MSDN a DateTime.Now.ToString("d")看起来像这样:6/15/2008(编辑:取决于您的本地文化,它可能导致一个有效的文件名)

斜杠在文件名中无效

replace

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

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

这是因为您的名字将解析为"7/29/2015MyNametest.txt"或其他包含无效字符的内容,具体取决于您的机器的区域性。我给出的例子显然不是一个有效的文件路径。我们必须去掉斜杠(/)。

将此问题视为Windows和Linux下的文件命名指南