我试图将我的所有数据写入文本文件,除非我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()方法应该创建一个新文件或覆盖已存在的文件.
有什么建议?
您可能希望确保路径有效且日期时间字符串不包含无效字符:
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)
| 归档时间: |
|
| 查看次数: |
7700 次 |
| 最近记录: |