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

XML attachment decoded to MemoryStream doesn't work

我的应用程序读取 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);