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

时间:2019-04-17 20:59:37

标签: 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));  

1 个答案:

答案 0 :(得分:3)

您需要先将视频流倒回到开头,然后再尝试加载。

换句话说,这样做:

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