2016-09-06 71 views
-1

我有一塊應該將覆蓋的文件發送到我的桌面,但代碼似乎沒有工作,我正在使用MVC應用程序而不是控制檯應用程序。如何使用Streamwriter將文件寫入桌面

任何人都可以告訴我我做錯了什麼或建議我如何實現我的解決方案。

using (var File = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "~/ColTexOutputFileTest.csv", false)) // true for appending the file and false to overwrite the file 
{ 
    foreach (var item in outputFile) 
    { 
     File.WriteLine(item); 
    } 
} 
+3

「但代碼似乎並不奏效「 - 你是什麼意思?你有什麼異常嗎?如果是這樣,在這裏發佈一些細節。 –

+3

如果這是一個MVC應用程序,您的桌面是否期望將其寫入?最終用戶還是服務器? –

回答

4

刪除'〜'字符。

"\ColTexOutputFileTest.csv" 
1

「〜」用於查找服務器端文件夾或文件

對於實例如果您在abc.xml文件

HttpContext.Current.Server.MapPath("~/App_Data/abc.xml"); 

訪問App_Data文件夾,如果你在流文件時,此字本地訪問文件爲windows路徑

using (var File = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\ColTexOutputFileTest.csv", false)) // true for appending the file and false to overwrite the file 
{ 
    foreach (var item in outputFile) 
    { 
     File.WriteLine(item); 
    } 
} 

「〜/ ColTexOutputFileTest.csv」 改變它 「\ ColTexOutputFileTest.csv」

1

如上答案所述,〜是問題所在。 .NET提供了對加入路徑&文件名&不需要知道是否需要隔離一個結合方法Path類:

using (var File = new StreamWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "ColTexOutputFileTest.csv"), false)) 

參見:https://msdn.microsoft.com/en-us/library/system.io.path(v=vs.110).aspx

相關問題