简体   繁体   中英

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. It is just creating a new file with the name= UserID + "HistoricalRecords.csv" and with no content. Any idea how to fix this?

You are not sending the file created to the client. Replace

HttpContext.Current.Response.BinaryWrite(bytes);

with

HttpContext.Current.Response.WriteFile(fileName);

Try this

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

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