I need to write an “object” to a file in C#, but all my attempts so far didn’t work. The problem is that the object I want to write really is of type object as it is returned from the Attachments collection of a MailItem object from an Outlook e-mail.
I already managed to insert it into a SQL Server database, retrieve and successfully create a correct file from it, but this can’t be the only way to go.
I also tried using BinaryFormatter as shown below, but this always corrupts my file header by adding some unwanted characters at the start (the remaining data seems to be okay):
[...]
using ( FileStream fileStream = new FileStream( tempName, FileMode.Create ) )
{
using ( BinaryWriter binaryWriter = new BinaryWriter( fileStream ) )
{
using ( MemoryStream memoryStream = new MemoryStream() )
{
object attachmentData =
attachment.PropertyAccessor.GetProperty( PR_ATTACH_DATA_BIN );
BinaryFormatter binaryFormatter =
new BinaryFormatter();
binaryFormatter.Serialize( memoryStream, attachmentData );
memoryStream.Seek( 0, SeekOrigin.Begin );
binaryWriter.Write( memoryStream.ToArray() );
}
}
}
[...]
Any ideas? I cannot control what I get from Outlook, so the usual serialization approach doesn’t seem to be what I need here…
I think this is what you are looking for:
How to: Save attachments from outlook