I use DataContractSerializerto serialize EF4 objects in xml if there are exceptions. In my debug log, I see what I want - this is content content when something went wrong.
I have two versions of code: one version that is serialized to a file, and which is serialized to a string using StringWriter.
When serializing large elements to a file, I can get xml about 16kb. when serializing the same element, the xml string is truncated after 12kb. Any idea what caused the truncation?
...
var entity = ....
SaveAsXml(entity, @"c:\temp\EntityContent.xml");
var xmlString = GetAsXml(entity);
System.Diagnostics.Debug.Writeline(xml.Substring(12200));
Any ideas why my string is truncated?
Here is the code to serialize to a file that works fine
public static void SaveAsXml(object objectToSave, string filenameWithPath)
{
string directory = Path.GetDirectoryName(filenameWithPath);
if (!Directory.Exists(directory))
{
logger.Debug("Creating directory on demand " + directory);
Directory.CreateDirectory(directory);
}
logger.DebugFormat("Writing xml to " + filenameWithPath);
var ds = new DataContractSerializer(objectToSave.GetType(), null, Int16.MaxValue, true, true, null);
var settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NamespaceHandling = NamespaceHandling.OmitDuplicates,
NewLineOnAttributes = true,
};
using (XmlWriter w = XmlWriter.Create(filenameWithPath, settings))
{
ds.WriteObject(w, objectToSave);
}
}
here is the code that serializes into a string to be truncated
public static string GetAsXml(object objectToSerialize)
{
var ds = new DataContractSerializer(objectToSerialize.GetType(), null, Int16.MaxValue, true, true, null);
var settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NamespaceHandling = NamespaceHandling.OmitDuplicates,
NewLineOnAttributes = true,
};
using (var stringWriter = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
{
try
{
ds.WriteObject(xmlWriter, objectToSerialize);
return stringWriter.ToString();
}
catch (Exception ex)
{
return "cannot serialize '" + objectToSerialize + "' to xml : " + ex.Message;
}
}
}
}