Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a Dictionary<int, object> in C# - Serialization?

I have a dictionary in c#

private Dictionary<int, UserSessionInfo> userSessionLookupTable = new Dictionary<int, UserSessionInfo>();

Now I have created a dictionary object

this.userSessionLookupTable.Add(userSessionInfoLogin.SessionId, userSessionInfoLogin);

Now I want a generic method to serialize and de-serialize the dictionory to byte array. Like

public static void Serialize(Dictionary<int, object> dictionary, Stream stream)
{
 //Code here
}

and

public static static Dictionary<int, object> Deserialize(Stream stream)
{
 //Code here
}

Can anyone help me on this??

like image 887
S M Avatar asked Oct 21 '25 09:10

S M


1 Answers

Try this....

    public static void Serialize<Object>(Object dictionary, Stream stream)
    {
        try // try to serialize the collection to a file
        {
            using (stream)
            {
                // create BinaryFormatter
                BinaryFormatter bin = new BinaryFormatter();
                // serialize the collection (EmployeeList1) to file (stream)
                bin.Serialize(stream, dictionary);
            }
        }
        catch (IOException)
        {
        }
    }

    public static Object Deserialize<Object>(Stream stream) where Object : new()
    {
        Object ret = CreateInstance<Object>();
        try
        {
            using (stream)
            {
                // create BinaryFormatter
                BinaryFormatter bin = new BinaryFormatter();
                // deserialize the collection (Employee) from file (stream)
                ret = (Object)bin.Deserialize(stream);
            }
        }
        catch (IOException)
        {
        }
        return ret;
    }
    // function to create instance of T
    public static Object CreateInstance<Object>() where Object : new()
    {
        return (Object)Activator.CreateInstance(typeof(Object));
    }

Usage...

        Serialize(userSessionLookupTable, File.Open("data.bin", FileMode.Create));
        Dictionary<int, UserSessionInfo> deserializeObject = Deserialize<Dictionary<int, UserSessionInfo>>(File.Open("data.bin", FileMode.Open));

I have used 'Object' in the code above to fulfil your requirements but personally I would use 'T' which usually denotes a generic object in C#

like image 187
Monty Avatar answered Oct 24 '25 01:10

Monty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!