如何解决C#文件附加内容到字符串
| 我正在尝试从电子邮件的附件中获取内容。我能够阅读电子邮件及其所有属性。附件是一个文本文件(.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
}
解决方法
那是因为它是一个字节数组,您必须使用StreamReader来获取它
var stream = new System.IO.MemoryStream(fileAttachment.Content);
var reader = new System.IO.StreamReader(stream,UTF8Encoding.UTF8);
var text = reader.ReadToEnd();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。