I have an XML document, which is 7,917 characters. It's read into an XElement using LINQ to XML, but I need to map/convert/adapt this XElement to a string (to send to a web service).
Here is my method:
public string AdaptXElementToString(XElement xml)
{
Encoding encoding = Encoding.GetEncoding(SpecializedEncodings.Iso88591);
using (MemoryStream memoryStream = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings { Encoding = encoding };
memoryStream.SetLength(21*1024*1024);
using (XmlWriter writer = XmlWriter.Create(memoryStream, settings))
{
xml.WriteTo(writer);
memoryStream.Flush();
string xmlText = encoding.GetString(memoryStream.ToArray());
return xmlText;
}
}
}
When I call this method, I can see using Intellisense that 'xml' has the entire contents of my file. However, the string xmlText gets chopped off at the 6144th character (which is 6 KB exactly). Because the xmlText is getting chopping off, I'm losing 1773 characters.
Does anyone know why this method isn't returning the entire string? I set the length of the memory stream buffer to 21 MB to ensure that it's big enough (even though the default constructor supports resizing).
I get the same behavior if I remove the call to SetLength(). I also get the same behavior if I remove the call to Flush().
For my purposes, I must use encoding ISO-8859-1, so I can't change to UTF-8 or 16.
Any help is greatly appreciated!
Solved the problem:
use writer.Flush(); not memoryStream.Flush()