简体   繁体   中英

how to write a file to desktop using streamwriter

I have a block which is supposed to send the overwritten file to my desktop but the code does not seem to be working, I am using a MVC application not a console apllication.

Can anyone tell me what I am doing wrong or advise me on how to achieve my solution.

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"

This character ' ~ ' used to find Server Side folder or file

For Example if you access App_Data folder in abc.xml file

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

if you streamed file on local access to file as windows path

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" change it "\\ColTexOutputFileTest.csv"

As stated in the answers above, the ~ is the problem. .Net provides the Path class which has a combine method for joining path & file names & not needing to know whether separators are needed :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM