Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
881 views
in Technique[技术] by (71.8m points)

file io - C#: Writing a CookieContainer to Disk and Loading Back In For Use

I have a CookieContainer extracted from a HttpWebRequest/HttpWebResponse session named CookieJar. I want my application to store cookies between runs, so cookies collected in the CookieContainer on one run of the program will be used the next run, too.

I think the way to do this would be to somehow write the contents of a CookieContainer to disk. My question is:

  • How can you write a CookieContainer to the disk? Are there built-in functions for this, or, if not, what are the approaches people have taken? Are there any classes available for simplifying this?
  • Once you've written a CookieContainer to the disk, how do you load it back in for use?

UPDATE: The first answer has suggested serialization of the CookieContainer. However, I am not very familiar with how to serialize and deserialize such complex objects. Could you provide some sample code? The suggestion was to utilise SOAPFormatter.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This problem was bugging me for ages, nothing I could find worked. I worked it out, so putting that information out into the world.

Answer using BinaryFormatter:

    public static void WriteCookiesToDisk(string file, CookieContainer cookieJar)
    {
        using(Stream stream = File.Create(file))
        {
            try {
                Console.Out.Write("Writing cookies to disk... ");
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, cookieJar);
                Console.Out.WriteLine("Done.");
            } catch(Exception e) { 
                Console.Out.WriteLine("Problem writing cookies to disk: " + e.GetType()); 
            }
        }
    }   

    public static CookieContainer ReadCookiesFromDisk(string file)
    {

        try {
            using(Stream stream = File.Open(file, FileMode.Open))
            {
                Console.Out.Write("Reading cookies from disk... ");
                BinaryFormatter formatter = new BinaryFormatter();
                Console.Out.WriteLine("Done.");
                return (CookieContainer)formatter.Deserialize(stream);
            }
        } catch(Exception e) { 
            Console.Out.WriteLine("Problem reading cookies from disk: " + e.GetType()); 
            return new CookieContainer(); 
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...