1

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Noich
  • 14,631
  • 15
  • 62
  • 90
  • 2
    Have you tried `streamWriter.Flush()`? – L.B Dec 30 '12 at 13:56
  • Have you tried `testElement.Save(contentStream);`? `StreamWriter.Write(object)` is not really meant for writing XML, although it's a bit odd that using this omits some parts of the XML returned by `XElement.ToString()`. – dtb Dec 30 '12 at 14:03
  • Thanks for the link. I added the 'C#' tag since some of my previous questions were edited to add tags to their titles. – Noich Dec 31 '12 at 13:24

2 Answers2

0

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

Noich
  • 14,631
  • 15
  • 62
  • 90
-1

Write [Serializable] above class like this way

[Serializable]
public class myClass{
//TODO: Your code here 

}

try it and feed me back

Nour Berro
  • 25
  • 8
  • XmlReaders/XmlSerializers don't require `Serializable` attribute. It is only needed for `BinaryFormatter`. – L.B Dec 30 '12 at 14:11
  • 1
    The XML wasn't serialized. It was read from a file and this information was sent to de-serializtion. – Noich Dec 31 '12 at 06:22