Search code examples
c#serializationstreamxelement

using StreamReader to read XElement leaves open elements


I have a MemoryStream that contains XML which I write to a file as follows:

var xml = XElement.Load(data.Content); // data.Content is of type `Stream`
var contentElement = new XElement("Content", xml);
var information = new XElement("TestInformation",
                      new XAttribute("Name", data.Descriptor.Name),
                      new XAttribute("Description", data.Descriptor.Description),
                      new XAttribute("Owner", data.Descriptor.Owner),
                      contentElement);

(data is an internal type - DataObject - that contains a Stream (called content) and a descriptor with metadata).

Later I try to read from this file as follows:

var returnValue = new DataObject();
var xElement = XElement.Load(fullPath);//the file path
returnValue.Descriptor = new Descriptor
                        {
                            Name = xElement.Attribute("Name").Value,
                            Description = xElement.Attribute("Description").Value,
                            Owner = xElement.Attribute("Owner").Value
                        };
returnValue.Content = GetContent(xElement.Element("Content"));

GetContent method:

private Stream GetContent(XElement element)
{
    var testElement = element.Elements().First();
    var contentStream = new MemoryStream();
    var streamWriter = new StreamWriter(contentStream);
    streamWriter.Write(testElement);
    contentStream.Position = 0;
    return contentStream;
}

When I try to read the stream as the internal type that I need, I get a SerializationException saying that some elements are not closed, and they really aren't - if I use a StreamReader to read this stream, it doesn't contain all the data that I saw in the XElement. What am I doing wrong here?


Solution

  • I was missing the use of StreamWriter.Flush(). This method causes the writer's buffer to be written to the stream.