开发者

C# fileattachment content to string

开发者 https://www.devze.com 2023-03-07 23:26 出处:网络
I am trying to get the content from an attachment on an email. I am able to read the email and all of its attributes. The attachment is a text file (.txt). How would i grab the actually text content o

I am trying to get the content from an attachment on an email. I am able to read the email and all of its attributes. The attachment is a text file (.txt). How would i grab the actually text content of the attachment? Below is a section of my code showing how i grab each email and then get its attributes and store them in the findResults list. Something like fileAttachment.Name would give me the name of the attachment. fileAttachment.content.tostring() will only show me 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
}   


That's because it is an array of bytes you'll have to use a StreamReader to get it

var stream = new System.IO.MemoryStream(fileAttachment.Content);
var reader = new System.IO.StreamReader(stream, UTF8Encoding.UTF8);
var text = reader.ReadToEnd();
0

精彩评论

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

关注公众号