Почему DataContractSerializer к StringWriter усекается? - PullRequest
5 голосов
/ 07 мая 2011

Я использую DataContractSerializer для сериализации объектов EF4 в XML, если есть исключения. В моем журнале отладки я вижу, что нужно было содержимое данных, когда что-то пошло не так.

У меня есть две версии кода: одна версия, которая сериализуется в файл, и другая, которая сериализуется в строку, используя StringWriter.

При сериализации больших элементов в файл я получаю действительный XML-файл размером около 16 КБ. при сериализации одного и того же элемента в строку xml обрезается после 12 КБ. Есть идеи, что вызвало усечение?

    ...
    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 Ответ

8 голосов
/ 07 мая 2011

Выход XmlWriter может не полностью сбрасываться при вызове ToString() на StringWriter.Попробуйте избавиться от объекта XmlWriter перед тем, как сделать это:

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