C#fileattachment内容为字符串

too*_*are 1 c# email exchange-server attachment exchangewebservices

我想从电子邮件中的附件中获取内容.我能够阅读电子邮件及其所有属性.附件是一个文本文件(.txt).我如何获取附件的实际文本内容?下面是我的代码的一部分,显示我如何获取每封电子邮件,然后获取其属性并将其存储在findResults列表中.像fileAttachment.Name这样的东西会给我附件的名称.fileAttachment.content.tostring()只显示system.Byte [].

FindItemsResults<Item> findResults = service.FindItems(fid1, new ItemView(int.MaxValue));
service.LoadPropertiesForItems(from Item item in findResults select item, PropertySet.FirstClassProperties);

foreach (Item item in findResults)
{
    String body = "";
    #region attachments
    if (ReadAttachments == "1")
    {
        EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));

        foreach (Attachment attachment in message.Attachments)
        {
            if (attachment is FileAttachment)
            {
                FileAttachment fileAttachment = attachment as FileAttachment;

                // Load the file attachment into memory and print out its file name.
                fileAttachment.Load();

                String attachbody = fileAttachment.Content.ToString();

                if (attachbody.Length > 8000)
                {
                    attachbody = attachbody.Substring(0, 8000);
                }
                Console.writeline(attachbody);
                #endregion

            }
        }
    }
    #endregion
}   
Run Code Online (Sandbox Code Playgroud)

小智 6

那是因为它是一个字节数组,你必须使用StreamReader来获取它

var stream = new System.IO.MemoryStream(fileAttachment.Content);
var reader = new System.IO.StreamReader(stream, UTF8Encoding.UTF8);
var text = reader.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)