I have an excel file (Excel 2003 / xls format) and I want to send it by email with c#. My code send it successfully, but when I try to open the response file, it seems to encoded wrongly.
For example here is the response filename:
=_utf-8_B_RWxzesOhbW9sw6FzXzIwMTJfMTBfMTZf.dat
And here is the response file itself:
=?utf-8?B?VEdWdmJIWmhjMkZ1Wk1Pelh6UXlYekZmPz0NCiA9P3V0Zi04P0I/VGtW?=\ \ =?utf-8?B?TlgwZFRXaTU0YkhNPT89?=" Content-Transfer-Encoding: base64 Content-Disposition: attachment
0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAABAAAA AQAAAAAAAAAAEAAAIwAAAAEAAAD+////AAAAAAAAAAD///////////////////// //////////////////////////////////////////////////////////////// ////////////////////////////// ....
Here is my code fragment:
...
var attachment = new Attachment(WriteFileToMemory("fileFullPath"), "fileName.xls");
attachment.ContentType = new ContentType("application/vnd.ms-excel");
attachmentCollection.Add(attachment);
...
private Stream WriteFileToMemory(string filePath)
{
var memoryStream = new MemoryStream();
_openedStreams.Add(memoryStream);
using (var file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
var bytes = new byte[file.Length];
file.Read(bytes, 0, (int) file.Length);
memoryStream.Write(bytes, 0, (int) file.Length);
file.Close();
}
memoryStream.Position = 0;
return memoryStream;
}
How can I set the attachment encoding type, and which encoding should I use with Excel files?
Please help me solve this problem. Thanks in advance.
You are making it too complex, as @Magnus points out, new Attachment()
can handle FileStream
s so just pass a new filestream to the constructor.
...
var attachment = new Attachment(File.Open("fileFullPath", FileMode.Open), "fileName.xls");
attachment.ContentType = new ContentType("application/vnd.ms-excel");
attachmentCollection.Add(attachment);
...
A word of warning though, kind is off topic, you cannot send a mail like that multiple times since the stream will not always reset itself properly.