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

Nau*_*nja 2 c# filestream

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

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

我得到这个例外:

mscorlib.dll中发生未处理的"System.IO.DirectoryNotFoundException"类型异常

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

有什么建议?

Fab*_*jan 7

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

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);
}
Run Code Online (Sandbox Code Playgroud)

最后将数据写入文件:

File.WriteAllText(path + filename,"HelloWorld");
Run Code Online (Sandbox Code Playgroud)


Ste*_*ler 5

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

斜杠在文件名中无效。