幽浮404

C#将CookieContainer保存到文件
将CookieContainer通过序列化保存到文件并读取 /// <summary> ...
扫描右侧二维码阅读全文
10
2019/11

C#将CookieContainer保存到文件

将CookieContainer通过序列化保存到文件并读取

    /// <summary>
    /// 保存cookie到文件
    /// </summary>
    /// <param name="file"></param>
    /// <param name="cookieJar"></param>
    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());
            }
        }
    }
    /// <summary>
    /// 读取cookie到文件
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    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();
        }
    }

同理也可将CookieContainer与string方便的互相转化

  public static string Serialize(Object Urobject) //序列化 返回string类型
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream memory = new MemoryStream();
        bf.Serialize(memory, Urobject);
        byte[] bytes = memory.GetBuffer();
        memory.Close();
        return Convert.ToBase64String(bytes);
    }

    public static object Deserialize(string str) //反序列化,返回object类型的
    {
        byte[] bytes = Convert.FromBase64String(str);
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream memory = new MemoryStream(bytes);
        object ss = bf.Deserialize(memory);
        memory.Close();
        return ss;
    }
Last modification:February 12th, 2020 at 06:03 pm
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment