Export different language content in .csv file in c#

2.1k Views Asked by At

I am trying to export data in a .csv file. Here, the data is in different languages (arabic, danish,.. etc).. the file can be exported successfully but the data content in the file are being replaced by ? and other symbols. i need to export the data as it is, in the .csv file. i tried with every possible way i found out on web but couldn't export the correct data. Can you please help me out.

Thanks

below is my code.

 protected void lnkExport_Click(object sender, EventArgs e)
        {
            List<Entities.Users_Users> lstUsers = new List<Entities.Users_Users>();

            lstUsers = BLL.Users_Users.GetDealerUsers(Convert.ToInt16(dealerid));

            StringBuilder sb = new StringBuilder();

            sb.Clear();

            sb.Append("[USERNAME],[PREFIX],[FIRSTNAME],[MIDDLENAME],[LASTNAME],[COMPANYNAME],[JOBTITLE],[CONTACTEMAILID],[USERTYPECODE],[STATUSCODE],[DEALER],[PHONE],[COMPANYLANGUAGE],[ISRECEIVECAMPAIGN],[RECEIVECAMPAIGNEMAILID]");

            sb.Append("\r\n");

            foreach (Entities.Users_Users UserDetail in lstUsers)
            { 
                sb.Append(UserDetail.UserName + "," + UserDetail.Prefix + "," + UserDetail.FirstName + "," + UserDetail.MiddleName + ",");
                sb.Append(UserDetail.LastName + "," + UserDetail.CompanyName + "," + UserDetail.JobTitle + ",");
                sb.Append(UserDetail.ContactEmailID + "," + UserDetail.UserTypeCode + "," + UserDetail.StatusCode + ",");
                sb.Append(UserDetail.DealerName + "," + UserDetail.Phone + "," + UserDetail.Language + ",");
                sb.Append(UserDetail.IsReceiveCampaign + "," + UserDetail.ReceiveCampaignEmailId);

                sb.Append("\r\n");
            }


            UTF8Encoding utf8 = new UTF8Encoding();


            var preamble = utf8.GetPreamble();

            var data = utf8.GetBytes(sb.ToString());



            //string attachment = String.Format("attachment;filename=ExportUsers.csv", "uomEncoded");
          //  Encoding encoding = Encoding.UTF8;
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = "text/csv";  
            Response.ContentEncoding = System.Text.Encoding.UTF8;
           // Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=ExportUsers.csv");
            //Response.Charset = "";
           // Response.Charset = encoding.EncodingName;


            Response.Write(sb.ToString());
            Response.Flush();
            Response.End();
        }
1

There are 1 best solutions below

3
On

That is what you probably missing (first line):

Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
Response.Write(sb.ToString());