【问题标题】:C# fileattachment content to stringC#文件附件内容到字符串
【发布时间】:2011-05-24 20:12:59
【问题描述】:

我正在尝试从电子邮件的附件中获取内容。我能够阅读电子邮件及其所有属性。附件是一个文本文件 (.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
}   

【问题讨论】:

    标签: c# email exchange-server attachment exchangewebservices


    【解决方案1】:

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

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

    【讨论】:

    • 很高兴我能提供帮助,而且 fileAttachment 可能已经包含一个 Stream 在这种情况下您不需要创建 MemoryStream 只需使用那个,并且您应该在完成使用后关闭阅读器(或使用,使用)。
    • 但是在这里,如果我尝试将其打印到控制台,例如 Console.Write(text),那么它会显示一些带有声音的符号结果。是某种错误还是我遗漏了什么??
    • 但它不适用于 .doc .xls 文件。它显示了一些象征性的结果。它适用于 .txt 文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 2017-11-08
    • 2023-01-11
    • 2014-11-18
    相关资源
    最近更新 更多