예외가있는 경우 DataContractSerializer
을 사용하여 EF4 개체를 XML로 serialize합니다. 디버그 로그에 뭔가 잘못되었을 때 데이터 콘텐츠가 필요하다는 것을 알 수 있습니다.StringWriter에 대한 DataContractSerializer가 잘리는 이유는 무엇입니까?
두 가지 버전의 코드가 있습니다. 하나는 파일에 직렬화되고 다른 하나는 StringWriter
을 사용하여 문자열로 직렬화됩니다.
큰 항목을 파일로 serialize 할 때 유효한 xml은 약 16kb입니다. xml과 동일한 항목을 직렬화 할 때 xml이 12kb 이후에 잘립니다. 왜 그 절단을 일으켰는데?
...
var entity = ....
SaveAsXml(entity, @"c:\temp\EntityContent.xml"); // ok size about 16100 btes
var xmlString = GetAsXml(entity); // not ok, size about 12200 bytes
// to make shure that it is not Debug.Writeline that causes the truncation
// start writing near the end of the string
// only 52 bytes are written although the file is 16101 bytes long
System.Diagnostics.Debug.Writeline(xml.Substring(12200));
왜 내 문자열이 잘리지 않습니까? 여기
여기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);
}
}
이
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;
}
}
}
}
1 : 솔루션을 작업을위한 감사합니다. 'return stringWriter.ToString();의 앞에'xmlWriter.Flush();'를 쓰는 대신 잘 작동합니다. – k3b