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

问题描述 投票:1回答:1

我的应用会读取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));  
c# mailkit
1个回答
3
投票

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

换句话说,这样做:

stream.Position = 0;
XDocument xDocument = XDocument.Load(stream);
© www.soinside.com 2019 - 2024. All rights reserved.