Skip to content

Instantly share code, notes, and snippets.

@htsign
Last active October 26, 2016 10:45
Show Gist options
  • Save htsign/400e738533498ca37b84d80cf35f4a33 to your computer and use it in GitHub Desktop.
Save htsign/400e738533498ca37b84d80cf35f4a33 to your computer and use it in GitHub Desktop.
Save/Load CookieContainer Sample
using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private const string DatName = "cookie.dat";
private readonly string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
private WebClientEx wc = new WebClientEx();
public Form1()
{
InitializeComponent();
}
private async void SaveCookiesAsync(string path)
{
using (var stream = File.OpenWrite(path))
{
await Task.Run(() =>
{
var bf = new BinaryFormatter();
bf.Serialize(stream, wc.CookieContainer);
});
await stream.FlushAsync();
}
}
private async Task<CookieContainer> LoadCookiesAsync(string path)
{
try
{
using (var stream = File.OpenRead(path))
{
return await Task.Run(() =>
{
var bf = new BinaryFormatter();
return (CookieContainer)bf.Deserialize(stream);
});
}
}
catch (FileNotFoundException e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
return null;
}
}
private async void Form1_Load(object sender, EventArgs e)
{
string path = Path.Combine(Desktop, DatName);
if (File.Exists(path))
{
wc.CookieContainer = await LoadCookiesAsync(path);
}
await wc.DownloadStringTaskAsync("");
SaveCookiesAsync(path);
}
}
}
using System;
using System.Net;
namespace WindowsFormsApplication1
{
public class WebClientEx : WebClient
{
public CookieContainer CookieContainer { get; set; } = new CookieContainer();
public string Referer { get; private set; }
protected override WebRequest GetWebRequest(Uri address)
{
var req = base.GetWebRequest(address);
if (req is HttpWebRequest)
{
((HttpWebRequest)req).CookieContainer = CookieContainer;
}
return req;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
var res = base.GetWebResponse(request);
Referer = (res as HttpWebResponse)?.ResponseUri.AbsoluteUri;
return res;
}
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
{
var res = base.GetWebResponse(request, result);
Referer = (res as HttpWebResponse)?.ResponseUri.AbsoluteUri;
return res;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment