Search code examples
c#serializationbinaryformatter

Is that possible to save a string variable and cookiecontainer in the same local file?


I need to use a string variable(a guid parameter) and a cookie container in other project and i need to keep theese locally. I am already keep cookie container and use that code below for it:

public static void WriteCookiesToDisk(string file, CookieContainer cookieJar)
        {
            using (Stream stream = File.Create(file))
            {
                try
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(stream, cookieJar);
                }
                catch (Exception e)
                {
                    Console.Out.WriteLine("Cookie yazdırılıken hata oluştu: " + e.GetType());
                }
            }
        }

I need to know is there a way to keep guid parameter(string var.) and cookie container in the same file and reach these in the other project as if they are variables.


Solution

  • Create a class to store both:

    [Serializable]
    public class Container
    {
        public string MyStringValue { get; set; }
        public CookieContainer Cookies { get; set; }
    }
    

    Create an instance with both objects in it:

    var objectToSerialize = new Container() { MyStringValue = "hello", Cookies = cookieJar };
    

    And then serialize it:

    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, objectToSerialize);