簡體   English   中英

不使用文件系統在C#中進行序列化

[英]Serialization in C# without using file system

我有一個簡單的2D字符串數組,我想把它填入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();

但這不起作用。 我發現的所有示例都演示了寫入文本文件。

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

這是一個通用序列化器(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);

將TextWriter和TextReader類與StringWriter一起使用。

以機智:

XmlSerializer s = new XmlSerializer(typeof(whatever));
TextWriter w = new StringWriter();
s.Serialize(w, whatever);
yourstring = w.ToString();

在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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM