· 1 min read

How to fix corrupt accented characters in Excel for a C# export as CSV

This post will help you fix the issue where you csv export has corrupt characters when opening it in excel.

This post will help you fix the issue where you csv export has corrupt characters when opening it in excel.

Here was the code before:

public HttpResponseMessage GetFileDownloadResponse(string fileName,string csvData)
{
    using (MemoryStream ms = new MemoryStream())
    {
        using (StreamWriter outfile = new StreamWriter(ms))
        {
            outfile.Write(csvData);
        }
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
        httpResponseMessage.Content = new ByteArrayContent(ms.ToArray());
        httpResponseMessage.Content.Headers.Add("x-filename", fileName);
        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/ms-excel");
        httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
        httpResponseMessage.StatusCode = HttpStatusCode.OK;
        return httpResponseMessage;
    }
}

We need to enable a BOM character that will tell Excel that the CSV file is in unicode

We do this by passing true when instaniating UTF8Encoding

here:

using (StreamWriter outfile = new StreamWriter(ms, new UTF8Encoding(true)))

and here:

httpResponseMessage.Content.Headers.ContentType.CharSet = new UTF8Encoding(true).HeaderName;

Here is the full code after:

public HttpResponseMessage GetFileDownloadResponse(string fileName,string csvData)
{

    using (MemoryStream ms = new MemoryStream())
    {
        using (StreamWriter outfile = new StreamWriter(ms, new UTF8Encoding(true)))
        {
            outfile.Write(csvData);
        }
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
        httpResponseMessage.Content = new ByteArrayContent(ms.ToArray());
        httpResponseMessage.Content.Headers.Add("x-filename", fileName);
        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/ms-excel");
        httpResponseMessage.Content.Headers.ContentType.CharSet = new UTF8Encoding(true).HeaderName;
        httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
        httpResponseMessage.StatusCode = HttpStatusCode.OK;
        return httpResponseMessage;
    }
}

Comments and reactions