如何用c#编写文件

本文关键字:文件 何用 | 更新日期: 2023-09-27 18:17:51

 string attachment = "attachment; filename=Myfile.csv";
 HttpContext.Current.Response.Clear();
 HttpContext.Current.Response.ClearHeaders();
 HttpContext.Current.Response.ClearContent();
 HttpContext.Current.Response.AddHeader("content-disposition", attachment);
 HttpContext.Current.Response.ContentType = "text/csv";
 HttpContext.Current.Response.AddHeader("Pragma", "public");
// My logic goes here to write file.
// Now I want to copy above file to another file.
 string filepath = Server.MapPath("~/ExportedFiles/") +"Newfile.csv";
 var ExcelFile = File.Create(filepath);
 ExcelFile.Close();
 HttpContext.Current.Response.TransmitFile(filepath);
 HttpContext.Current.Response.Flush();

以上代码不工作,请建议我。谢谢。

如何用c#编写文件

您需要在IIS上创建一个虚拟目录并共享该虚拟目录目录。您的csv应该驻留在虚拟目录共享位置。这里是参考文章:http://www.codeproject.com/Tips/502741/A-solution-to-problem-Response-TransmitFile

使用以下代码而不是:var ExcelFile = File.Create(filepath);c#中的WriteAllLines指令用于创建文件或更改内容文件

File.WriteAllLines(filepath, data);