开发者

.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, attac开发者_运维技巧hBytes.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);


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

message.BodyEncoding = UTF8


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);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜