C# Generate File wiht UTF8 BOM - JackHu88/Comm GitHub Wiki
protected void Export(string str)
{
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
try
{
Encoding encoding = Encoding.UTF8;
var bytes = encoding.GetBytes(str);
//add the BOM
byte[] bBOM = new byte[] { 0xEF, 0xBB, 0xBF };
byte[] bContent = bytes;
byte[] bToWrite = new byte[bBOM.Length + bContent.Length];
//combile the BOM and the content
bBOM.CopyTo(bToWrite, 0);
bContent.CopyTo(bToWrite, bBOM.Length);
//Response.Write(Encoding.UTF8.GetString(bToWrite));
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", fileName));
Response.ContentType = "application/text";
Response.Output.Write(Encoding.UTF8.GetString(bToWrite));
Response.Flush();
Response.End();
}
catch(System.Threading.ThreadAbortException)
{
}
catch (Exception err)
{
ClientScript.RegisterStartupScript(this.GetType(), "Message", "alert('" + err.Message + "');", true);
}
}