简体   繁体   中英

Download file with non-english character in C# using HttpResponse

I am trying to build a functionality to download a csv file in C#.

When the name of the file has non-english character, the downloaded file does not seems to have the correct name. However in the network tab, the response header has the same Content-Disposition value, as given in the code.

Sample Code

private void PopulateCsvInResponse(MemoryStream csvData, string fileName)
{
    HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    //actual file name "Москва.csv"
    response.AddHeader("Content-Disposition", "attachment; filename=%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0.csv");
    byte[] byteArray = csvData.ToArray();
    response.AddHeader("Content-Length", byteArray.Length.ToString());
    response.ContentType = "text/csv; charset=utf-8";
    response.BinaryWrite(byteArray);
    response.Flush();
    response.Close();
}

For example the file name is Москва.csv .
UTF-8 encoded name: %D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0.csv .

Things that I tried

Replacing Content-Disposition header

Attempt 1

response.AddHeader("Content-Disposition", 
   "attachment; filename=Москва.csv");   

The downloaded file name is

Ð_оÑ_ква


Attempt 2

response.AddHeader("Content-Disposition", 
   "attachment; filename=\"%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0.csv\"; filename*=UTF-8''%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0.csv");

The downloaded file name is

_%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0.csv_; filename_


Attempt 3

response.AddHeader("Content-Disposition", 
    "attachment; filename=%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0.csv");

The downloaded file name is

%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0.csv


Attempt 4

response.AddHeader("Content-Disposition", 
    "attachment; filename*=UTF-8''%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0.csv");

The downloaded file name is

UTF-8''%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0.csv

I finally found out the solution.
The issue was never with above code, it was always working fine. The actual issue was in front end, where the content disposition header that was received in encode was not decoded, and I skipped to see this part when I raised the question.
I thought of deleting this question, but keeping it so that if someone makes the same silly mistake as me, might realise it earlier instead of wasting time to look for solution for the problem that never existed.

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