簡體   English   中英

如何使用Streamwriter將文件寫入桌面

[英]how to write a file to desktop using streamwriter

我有一個應該將覆蓋文件發送到我的桌面的塊,但是代碼似乎不起作用,我使用的是MVC應用程序,而不是控制台應用程序。

誰能告訴我我做錯了什么,或就如何實現我的解決方案建議我。

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"

此字符'〜'用於查找服務器端文件夾或文件

例如,如果您訪問abc.xml文件中的App_Data文件夾

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

如果您將文件的本地訪問流式傳輸為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”

如以上答案中所述,〜是問題所在。 .Net提供了Path類,該類具有用於合並路徑和文件名的Combine方法,並且無需知道是否需要分隔符:

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

請參閱: https : //msdn.microsoft.com/zh-cn/library/system.io.path(v=vs.110).aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM