如何使用streamwriter将文件写入桌面

时间:2016-09-06 10:47:36

标签: c# asp.net-mvc 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);
    }
}

3 个答案:

答案 0 :(得分:4)

删除'〜'字符。

"\ColTexOutputFileTest.csv"

答案 1 :(得分:1)

此字符'〜'用于查找服务器端文件夹或文件

例如如果您访问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”

答案 2 :(得分: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

相关问题