开发者

Save an object in a file, or get the object in bytes?

开发者 https://www.devze.com 2023-02-01 18:49 出处:网络
I am wondering how I (in C# or VB .NET) can save an object to a file. It needs to be compatible with any type of object. How c开发者_StackOverflow中文版an I do this? Let\'s say I want to save an obje

I am wondering how I (in C# or VB .NET) can save an object to a file.

It needs to be compatible with any type of object. How c开发者_StackOverflow中文版an I do this? Let's say I want to save an object of the type "MyPersonClass".

I am using the .NET 4.0 framework, with WPF.


If you are looking for some control and compatibility with non .NET applications, consider using the SoapFormatter class (as outlined in John Boker's MSDN link) or XML serialisation. The latter works slightly differently from standard serialisation.

You require the XmlSerializer class:

System.Xml.Serialization.XmlSerializer

To serialize MyPersonClass using XML serialisation, you will need instances of XmlSerializer and StreamWriter (in System.IO):

XmlSerializer serializer = new XmlSerializer(typeof(MyPersonClass));
StreamWriter xmlFile = new StreamWriter(@"InsertFileName");
serializer.Serialize(xmlFile, classInstance);
xmlFile.Close();

I hope this is useful!


You should inherit your class from ISerializable interface. An example and explanation can be found following next link:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx


If you object is Serializable it can be serialized and persisted to disk with the methods described here: http://msdn.microsoft.com/en-us/library/4abbf6k0%28v=VS.100%29.aspx


First you have to mark your object as serializable:

[System.Serializable]
public class MyPersonClass
{
    public string Firstname
    {
        get;
        set;
    }

    public string Lastname
    {
        get;
        set;
    }
}

After that you can use the BinaryFormatter class to save each objects as bytes.

To bytes:

public static byte[] ObjectToBytes(object obj)
{
    byte[] objAsBlob;

    using (System.IO.MemoryStream temp = new System.IO.MemoryStream())
    {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        formatter.Serialize(temp, obj);

        objAsBlob = temp.ToArray();
    }

    return objAsBlob;
}

From bytes:

public static TObj BytesToObject<TObj>(byte[] blob)
{
    object objFromBytes;

    using (System.IO.MemoryStream temp = new System.IO.MemoryStream(blob))
    {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        objFromBytes = formatter.Deserialize(temp);
    }

    return (TObj)objFromBytes;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号