Ricky
Ricky

Reputation: 35833

.NET encoding issue of mail attachment (.csv)

I use following code to send a attachment (.csv) with Chinese characters. However, MS excel fails to disply the characters properly, it displays something like "¨å¯¹æ–°ç". Is it because I didn't set some property when sending the mail?

Thanks for any advise.

                byte[] attachBytes = Encoding.UTF8.GetBytes(attachText);
                ms.Write(attachBytes, 0, attachBytes.Length);
                // Set the position to the beginning of the stream.
                ms.Position = 0;
                ContentType ct = new ContentType(MediaTypeNames.Text.Plain);

                Attachment attactment = new Attachment(ms, attachFileName);
                message.Attachments.Add(attactment);

Upvotes: 5

Views: 1824

Answers (3)

Michael Offengenden
Michael Offengenden

Reputation: 91

I found some solution:

        byte[] bom = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF };
        var csvStr = Encoding.UTF8.GetString(bom) + csv.ToString();

Works fine for me

Upvotes: 0

Linus Caldwell
Linus Caldwell

Reputation: 11058

Setting the attachments encoding to Encoding.UTF32 could help. Assuming attachText is a string and you only want to add a .csv you could shorten your code by using the Attachment.CreateAttachmentFromString() method:

var attachment = Attachment.CreateAttachmentFromString(attachText,
                                                       "filename.csv",
                                                       Encoding.UTF32,
                                                       "text/csv");
message.Attachments.Add(attachment);

Upvotes: 2

Ali Tarhini
Ali Tarhini

Reputation: 5358

i think you need an extra encoding setup for the mail body object, something like this:

message.BodyEncoding = UTF8

Upvotes: 2

Related Questions