Recently, I am working on a small software that can log in and automatically send messages through HttpWebRequest. Although it has not been implemented yet, today I saw a good way to obtain cookieContainer from a foreign website. I took it out and shared it. This is what I saw. The code is minimal and very good.
1using System;
2using System.Runtime.InteropServices;
3using System.Text;
4using System.Net;
5
6namespace NExplos.NSiter
7{
8 /**//// <summary>
9 /// The method class to obtain cookies.
10 /// </summary>
11 public class CookieManger
12 {
13 /**/// <summary>
14 /// Get cookie data through COM.
15 /// </summary>
16 /// <param name=url>Current URL. </param>
17 /// <param name=cookieName>CookieName.</param>
18 /// <param name=cookieData> Used to save the <see cref=StringBuilder/> instance of Cookie Data. </param>
19 /// <param name=size>Cookie size. </param>
20 /// <returns> Returns <c>true</c> if successful, otherwise return <c>false</c>. </returns>
21 [DllImport(winet.dll, SetLastError = true)]
22 public static extern bool InternetGetCookie(
23 string url, string cookieName,
24 StringBuilder cookieData, ref int size);
25 /**//// <summary>
26 /// Get the current <see cref=CookieContainer/instance of <see cref=Uri/>.
27 /// </summary>
28 /// <param name=uri>The current <see cref=Uri/> address. </param>
29 /// <returns> The current <see cref=CookieContainer/instance of <see cref=Uri/>. </returns>
30 public static CookieContainer GetUriCookieContainer(Uri uri) {
31 CookieContainer cookies = null;
32
33 // Define the size of the cookie data.
34 int datasize = 256;
35 StringBuilder cookieData = new StringBuilder(datasize);
36
37 if (!InternetGetCookie(uri.ToString(), null, cookieData,
38 ref datasize)) {
39 if (datasize < 0)
40 return null;
41
42 // Confirm that there is enough space to accommodate cookie data.
43 cookieData = new StringBuilder(datasize);
44 if (!InternetGetCookie(uri.ToString(), null, cookieData,
45 ref datasize))
46 return null;
47 }
48
49
50 if (cookieData.Length > 0) {
51 cookies = new CookieContainer();
52 cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
53 }
54 return cookies;
55 }
56
57 }
58} Isn't it quite simple? I hope it will be useful to everyone.