c# - 解码到 MemoryStream 的 XML 附件不起作用

标签 c# mailkit

我的应用程序读取 Gmail 的附件。附件是一种 XML 文件(特别是 .tcx)。当我将它们解码为 MemoryStream 时,出现错误

XDocument.Load(stream): 

System.Xml.XmlException
  HResult=0x80131940
  Message=Root element is missing.
  Source=System.Private.Xml
  StackTrace:
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
   at System.Xml.Linq.XDocument.Load(Stream stream, LoadOptions options)
   at System.Xml.Linq.XDocument.Load(Stream stream)

但是当我将它解码为 FileStream 时一切正常。

失败代码:

foreach (var attachment in message.Attachments)
{
    var stream = new MemoryStream();

    if (attachment is MessagePart rfc822)
    {
        rfc822.Message.WriteTo(stream);
    }
    else
    {
        var part = (MimePart)attachment;
        part.Content.DecodeTo(stream);
    }
    XDocument xDocument = XDocument.Load(stream);
}

但是如果我使用 FIleStream,它会起作用:

using (var stream = File.Create(fileName))
{
    if (attachment is MessagePart rfc822)
    {
        rfc822.Message.WriteTo(stream);
    }
    else
    {
        var part = (MimePart)attachment;
        part.Content.DecodeTo(stream);
    }
}

XDocument xDocument = XDocument.Load(File.Open(fileName, 
FileMode.OpenOrCreate));  

最佳答案

在尝试加载流之前,您需要将流倒回到开头。

换句话说,这样做:

stream.Position = 0;
XDocument xDocument = XDocument.Load(stream);

关于c# - 解码到 MemoryStream 的 XML 附件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55735874/

相关文章:

c# - 我的问题是关于向对象添加更多字符串条目

c# - .NET 随机 RGB 颜色

c# - 如何在 C# 中使用 MimeKit 发送电子邮件

Mailkit IMAP gmail - 如何发送?在线 Doumentation 没有显示如何发送示例

c# - MailKit 中的 SMTP 服务器意外断开连接

c# - Mailkit 对 Imap 的身份验证失败

c# MailKit - 阅读回执

c# - 从WCF获取数据

c# - 访问 C# 属性名称或特性

c# - 用户控制按钮点击事件