[转].Net/C# 应用程序直接读取本地 Cookies 文件

.net/C#应用程序直接读取本地Cookies文件(WinXPSP2调用API:InternetGetCookie)

 1 usingSystem;
2 usingSystem.IO;
3 usingSystem.Text;
4 usingSystem.Text.RegularExpressions;
5 usingMicrosoft.Win32;
6 publicclassClass1
7 {
8 staticvoidMain(string[]args)
9 {
10 System.Console.WriteLine(GetCookiesFromFiles("et8"));//支持WinXPSP2
11 System.Console.WriteLine(GetCookie("http://bbs.et8.net"));
12 }
13 [System.Runtime.InteropServices.DllImport("wininet.dll",CharSet=System.Runtime.InteropServices.CharSet.Auto,SetLastError=true)]
14 publicstaticexternboolInternetGetCookie(stringlpszUrlName,stringlpszCookieName,StringBuilderlpszCookieData,refintlpdwSize);
15 [System.Runtime.InteropServices.DllImport("kernel32.dll")]
16 internalstaticexternInt32GetLastError();
17 publicstaticstringGetCookie(stringurl)//Win32API
18 {
19 intsize=1000;
20 StringBuildersb=newStringBuilder(size);
21 if(!InternetGetCookie(url,"",sb,refsize))
22 {
23 Console.WriteLine("Errorcode:{0}",GetLastError());
24 }
25 returnsb.ToString();
26 }
27 publicstaticstringGetCookiesFromFiles(stringMasterDomain)//CookiesFile
28 {
29 stringS=null;
30 ReGIStryKeykey=Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ShellFolders",false);
31 if(key!=null)
32 {
33 stringval=(string)key.GetValue("Cookies");
34 if(val!=null)
35 {
36 string[]F=Directory.GetFiles(val);
37 strings=null;
38 inti;
39 Regexr=newRegex(@".*@" MasterDomain @"*\[\d \].txt");
40 for(i=0;i<F.Length;i )
41 {
42 if(r.IsMatch(F[i]))
43 {
44 s=F[i];
45 }
46 }
47 if(s!=null)//s就是最新文件
48 {
49 StreamReadersr=newStreamReader(s);
50 s=null;
51 i=1;
52 while((s=sr.ReadLine())!=null)
53 {
54 if(s=="*"||s=="\n")
55 {
56 i=0;
57 }
58 //每节只读两行
59 if(i==1)
60 {
61 S =s;
62 }
63 elseif(i==2)
64 {
65 S ="=" s ";";
66 }
67 i ;
68 }
69 }
70 }
71 }
72 returnS;
73 }
74 }