简体   繁体   English

从特定文件夹导出文件以供客户端下载

[英]Exporting a file from a specific folder for client to download

I want to export a file from a specific folder which the client will download. 我想从客户端将下载的特定文件夹中导出文件。 My code is below: 我的代码如下:

string Name = UserID + "HistoricalRecords.csv";
string fileName = "C:\\Temp\\"+Name;
TextWriter textWriter = new StreamWriter(fileName);

/*Some codes which add data to the csv.*/

byte[] bytes = Encoding.ASCII.GetBytes(textWriter.ToString());
        if (bytes != null)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "text/csv";
            HttpContext.Current.Response.AddHeader("Content-Length", bytes.Length.ToString());
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "Attachment; Filename=" + fileName + "");
            HttpContext.Current.Response.BinaryWrite(bytes);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

The file is created with the good content in the specified folder. 在指定的文件夹中创建具有良好内容的文件。 However, the file which the client is downloading is not the file from the specific folder "C:\\Temp\\" with the data as content. 但是,客户端下载的文件不是特定文件夹“ C:\\ Temp \\”中以数据为内容的文件。 It is just creating a new file with the name= UserID + "HistoricalRecords.csv" and with no content. 它只是使用名称= UserID +“ HistoricalRecords.csv”创建一个没有内容的新文件。 Any idea how to fix this? 任何想法如何解决这个问题?

You are not sending the file created to the client. 您没有将创建的文件发送给客户端。 Replace 更换

HttpContext.Current.Response.BinaryWrite(bytes); HttpContext.Current.Response.BinaryWrite(bytes);

with

HttpContext.Current.Response.WriteFile(fileName); HttpContext.Current.Response.WriteFile(fileName);

Try this 尝试这个

  HttpContext.Current.Response.ClearHeaders();
  HttpContext.Current.Response.ClearContent();
  HttpContext.Current.Response.ContentType = "application/CSV";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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