26

我有一个简单的二维字符串数组,我想将它填充到 MOSS 中的 SPFieldMultiLineText 中。这映射到一个 ntext 数据库字段。

我知道我可以序列化为 XML 并存储到文件系统,但我想在不接触文件系统的情况下进行序列化。

public override void ItemAdding(SPItemEventProperties properties)
{
    // build the array
    List<List<string>> matrix = new List<List<string>>();
    /*
    * populating the array is snipped, works fine
    */
    // now stick this matrix into the field in my list item
    properties.AfterProperties["myNoteField"] = matrix; // throws an error
}

看起来我应该能够做这样的事情:

XmlSerializer s = new XmlSerializer(typeof(List<List<string>>));
properties.AfterProperties["myNoteField"] = s.Serialize.ToString();

但这不起作用。我发现的所有示例都演示了写入文本文件。

4

4 回答 4

40
StringWriter outStream = new StringWriter();
XmlSerializer s = new XmlSerializer(typeof(List<List<string>>));
s.Serialize(outStream, myObj);
properties.AfterProperties["myNoteField"] = outStream.ToString();
于 2008-11-19T18:32:48.810 回答
12

这是一个通用序列化程序(C#):

    public string SerializeObject<T>(T objectToSerialize)
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream memStr = new MemoryStream();

        try
        {
            bf.Serialize(memStr, objectToSerialize);
            memStr.Position = 0;

            return Convert.ToBase64String(memStr.ToArray());
        }
        finally
        {
            memStr.Close();
        }
    }

在您的情况下,您可以致电:

    SerializeObject<List<string>>(matrix);
于 2008-11-19T20:46:24.813 回答
5

将 TextWriter 和 TextReader 类与 StringWriter 一起使用。

以机智:

XmlSerializer s = new XmlSerializer(typeof(whatever));
TextWriter w = new StringWriter();
s.Serialize(w, whatever);
yourstring = w.ToString();
于 2008-11-19T18:37:51.327 回答
2

在 VB.NET 中

Public Shared Function SerializeToByteArray(ByVal object2Serialize As Object) As Byte()
    Using stream As New MemoryStream
        Dim xmlSerializer As New XmlSerializer(object2Serialize.GetType())
        xmlSerializer.Serialize(stream, object2Serialize)
        Return stream.ToArray()
    End Using
End Function

Public Shared Function SerializeToString(ByVal object2Serialize As Object) As String
    Dim bytes As Bytes() = SerializeToByteArray(object2Serialize)
    Return Text.UTF8Encoding.GetString(bytes)
End Function

在 C#

public byte[] SerializeToByteArray(object object2Serialize) {
       using(MemoryStream stream = new MemoryStream()) {
          XmlSerializer xmlSerializer = new XmlSerializer(object2Serialize.GetType());
          xmlSerializer.Serialize(stream, object2Serialize);
          return stream.ToArray();
       }
}

public string SerializeToString(object object2Serialize) {
   byte[] bytes = SerializeToByteArray(object2Serialize);
   return Text.UTF8Encoding.GetString(bytes);
}
于 2008-11-19T18:33:05.457 回答