2017-01-30 91 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("/", "-");