Solving the encoding problem while writing to Response

Technology: C# ASP.NET

Level: Expert

Depth: Medium

I, once, had to present a save-as dialogue that would export the content of a GridView into csv and the database would contain Japanese texts. Export was all fine and the file was read fine from Visual Studio itself. However, when the csv was opened from Excel, the Japanese texts came all garbage.

This could have been for my PC doesn’t have Japanese locales and fonts. But the PC with such features also read it same. Here I present a way that solved this problem.

protected void ImageButton_CSV_Click(object sender, ImageClickEventArgs e)

{

MyDataSet.MyDataTable exportTable = …

HttpContext context = HttpContext.Current;

context.Response.Clear();

context.Response.ContentEncoding = Encoding.GetEncoding(“shift_JIS”);

for (int i = 1; i < exportTable.Columns.Count; i++)

{

context.Response.Write(exportTable.Columns[i].ColumnName + “,”);

}

context.Response.Write(Environment.NewLine);

string orig_string = “”;

byte[] unicodeBytes = null;

byte[] codBytes = null;

char[] codChars = null;

string codString = “”;

Encoding cod = Encoding.GetEncoding(“shift_JIS”);

Encoding unicode = Encoding.UTF8;

for (int i = 1; i < exportTable.Rows.Count; i++)

{

for (int j = 0; j < exportTable.Columns.Count; j++)

{

orig_string = exportTable[i][j].ToString().Replace(“,”, string.Empty).Replace(“&nbsp;”, string.Empty) + “,”;

unicodeBytes = unicode.GetBytes(orig_string);

codBytes = Encoding.Convert(unicode, cod, unicodeBytes);

codChars = new char[cod.GetCharCount(codBytes, 0, codBytes.Length)];

cod.GetChars(codBytes, 0, codBytes.Length, codChars, 0);

codString = new string(codChars);

context.Response.Write(codString);

}

context.Response.Write(Environment.NewLine);

}

context.Response.ContentType = “text/csv”;

context.Response.AppendHeader(“Content-Disposition”, “attachment; filename=my_file.csv”);

context.Response.End();

}

The codes in the bold do the actual trick. The content encoding and writing to the response in the correct manner is all that needs to be done.

This, however, is not limited to csv exports. You can try with other file formats too.

Cheers and Cheese (Y)

1 Response to “Solving the encoding problem while writing to Response”


  1. 1 RRaveen July 2, 2009 at 10:28 am

    Dear Friends,

    I hope you are doing well. I have launched a web site http://www.codegain.com and it is basically aimed C#,JAVA,VB.NET,ASP.NET,AJAX,Sql Server,Oracle,WPF,WCF and etc resources, programming help, articles, code snippet, video demonstrations and problems solving support. I would like to invite you as an author and a supporter. Looking forward to hearing from you and hope you will join with us soon.

    Please forward this email to all of your friends who are related IT. Send to us your feed about site also.

    Thank you
    RRaveen
    Founder CodeGain.com


Leave a Reply