2017-01-30 68 views
1

我想为我的实习制作一个小小的Windows-Forms测验应用程序,我坚持将结果保存到保存文件。这是我使用的代码:c#路径格式不支持writealllines

string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); 

System.IO.File.WriteAllLines(desktopPath + @"\saveFile_" + DateTime.Now.ToString() + ".txt", saveFile); 

当我按一下按钮,保存到一个新的文本文件,它崩溃,并告诉我,该路径格式不支持。

我该如何纠正它,使其保存到桌面上的新文本文件?

+7

'DateTime.Now.ToString()'将包含一个':',它是一个[非法文件名字符](https://msdn.microsoft.com/de-de/library/system.io.path.getinvalidfilenamechars( v = vs.110)的.aspx)。 –

+3

在旁注中,如果有任何应用程序将文件转储到我的桌面,我不会很高兴 – dlatikay

回答

3

DateTime.Now.ToString()将产生类似于30.01.2017 10:30:0001/30/2017 10:30:00的字符串。

:invalid file name character所以你需要摆脱它,通过手动格式化时间戳它例如:同样

string filename = "saveFile_" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".txt" 

,我对建筑的路径建议用+,有一个内置函数即:

System.IO.Path.Combine(desktopPath, filename);  
// or if you have another folder for those files 
System.IO.Path.Combine(desktopPath, "FolderX", filename); 
0

只需用破折号代替斜杠:

DateTime.Now.ToString().Replace("/", "-"); 
相关问题