I have got a simple winform application. On the first run, a login screen is run so the user can login to a website. The session cookies are saved if its a success like so:
Properties.Settings.Default["cookies"] = cookies;
Properties.Settings.Default.Save();
After that's done, the login form gets hidden and a new main form gets run. In this mainform the cookiecontainer is read and saved again:
CookieContainer cookies = Properties.Settings.Default.cookies;
Works like a charm. The session cookies are still in there and everything is fine. After that, a new request is done to a website, using the cookies like so:
private string htmlGet(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "text/html";
request.CookieContainer = cookies;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
Works fine. Request is done and specific user-related data is found in the string.
However, one I restart the program something strange happens.
Before the program starts this code is run to check for first-run by looking at the cookies:
if (Properties.Settings.Default.cookies == null)
{
Application.Run(new login());
}
else
{
Application.Run(new main());
}
And indeed, after the first run, Properties.Settings.Default.cookies
is not null
, so the main form gets started by Program.cs
.
Weirdly enough, this time Properties.Settings.Default.cookies
returns a CookieContainer object... with no cookies.
I have no idea why, as my application settings only get saved in the login form, which is only opened on the first time run. Has anyone got any experiences with cookiecontainers doing something weird like this? Do I have to check for something in my code perhaps? Cheers.