如何在C#中将对象写入二进制文件?

时间:2012-07-09 08:03:21

标签: c# .net file object binary

我需要在C#中为文件写一个“对象”,但到目前为止我的所有尝试都没有用。问题是我想写的对象实际上是object类型,因为它是从Outlook电子邮件中Attachments对象的MailItem集合返回的。

我已经设法将其插入到SQL Server数据库中,从中检索并成功创建了一个正确的文件,但这不是唯一的方法。

我也尝试使用BinaryFormatter,如下所示,但这总是通过在开始时添加一些不需要的字符来破坏我的文件头(其余数据似乎没问题):

[...]
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() );
        }
    }
}
[...]

有什么想法吗?我无法控制从Outlook获得的内容,因此通常的序列化方法似乎不是我需要的...

1 个答案:

答案 0 :(得分:5)

我认为这就是你要找的东西:

How to: Save attachments from outlook

if (newEmail.Attachments.Count > 0)
{
      for (int i = 1; i <= newEmail.Attachments.Count; i++)
      {
           newEmail.Attachments[i].SaveAsFile
                (@"C:\TestFileSave\" +
                newEmail.Attachments[i].FileName);
      }
}