Как сериализовать CookieContainer в приложениях wp7?

Я попытался сериализовать файл cookie, чтобы сохранить его, и выполнить десериализацию при следующем запуске приложения, но результат десериализации оказался пустым. Что не так?

void SaveCookie() {
    var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
    if (this.checkBox_save_passowrd.IsChecked == true)
    {
        CookieContainer cc = SEC_Services.Httprequest.cookie;
        string fileName = "usercookie.xml";
        using (var file = appStorage.OpenFile(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
        {
            using (var writer = new StreamWriter(file))
            {
                System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(CookieContainer));
                xs.Serialize(writer, cc);
                writer.Close();
            }
        }
    }
    else {
        if (appStorage.FileExists("usercookie.xml"))
        {
            appStorage.DeleteFile("usercookie.xml");
        }
    }
}

void ReadCookie() {
    var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
    if (appStorage.FileExists("usercookie.xml"))
    {
        using (System.IO.StreamReader reader = new StreamReader(appStorage.OpenFile("usercookie.xml", FileMode.Open)))
        {
            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(CookieContainer));
            CookieContainer obj = (CookieContainer)xs.Deserialize(reader);
            reader.Close();
            SEC_Services.Httprequest.cookie = obj;
            if (obj.Count != 0) {
                NavigationService.Navigate(new Uri("/PanoramaPage.xaml", UriKind.Relative));
            }
        }
    }
}

Я также нашел этот простой C #: Writing CookieContainer на диск и загрузка обратно для использования показывает, что CookieContainer может быть сериализован, но в библиотеке wp7 нет SoapFormatter


person Shisoft    schedule 08.02.2011    source источник


Ответы (2)


IsolatedStorageSettings.ApplicationSettings["index"] = yourcookie;

Так что вам не нужно его сериализовать.

Я использую это в проекте

person Morti    schedule 09.11.2011

Поскольку вопрос - «Как сериализовать CookieContainer», и принятый ответ на самом деле не отвечает на него. Вот как это сделать с сериализацией:

Записать на диск:

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(); 
        }
}
person LucidObscurity    schedule 15.01.2012
comment
В WP7 нет BinaryFormatter, поэтому этот ответ также не применим. - person Tony Kh; 01.12.2012
comment
Я не знал об этом! Попробуйте этот ответ: stackoverflow.com/a/1777234/1099131 - person LucidObscurity; 08.03.2013