2011-05-07 13 views
5

Estoy utilizando el DataContractSerializer para serializar objetos EF4 a xml si hay excepciones. En mi registro de depuración puedo ver que quería era el contenido de datos cuando algo salió mal.¿Por qué DataContractSerializer to StringWriter está truncado?

Tengo dos versiones de código: una versión que se serializa en un archivo y otra que se serializa en una cadena usando StringWriter.

Al serializar elementos grandes en el archivo obtengo xml válido de aproximadamente 16kb. al serializar el mismo elemento en la cadena, el xml se trunca después de 12kb. ¿Alguna idea de lo que causó el truncamiento?

... 
    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)); 

¿Alguna idea de por qué mi cadena está truncada?

Este es el código para serializar a archivos que funciona bien

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); 
    } 
    } 

Este es el código que serializa de cadena que se trunca

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; 
      } 
     } 
    } 
    } 

Respuesta

8

de salida El XmlWriter 's podría no ser completamente sonrojado cuando invoca ToString() en el StringWriter. Intente eliminar el objeto XmlWriter antes de hacerlo:

try 
{ 
    using (var stringWriter = new StringWriter()) 
    { 
     using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings)) 
     { 
      ds.WriteObject(xmlWriter, objectToSerialize); 
     } 
     return stringWriter.ToString(); 
    } 
} 
catch (Exception ex) 
{ 
    return "cannot serialize '" + objectToSerialize + "' to xml : " + ex.Message; 
} 
+1

+1: gracias por su solución de trabajo. En lugar de deshacerse de 'xmlWriter.Flush();' before 'return stringWriter.ToString();' también funciona. – k3b

Cuestiones relacionadas