1. 程式人生 > >C#獲取Internet臨時檔案,獲取Cookie檔案幫助類

C#獲取Internet臨時檔案,獲取Cookie檔案幫助類

  獲取Internet臨時檔案路徑,通過user.dll獲取到所有檔案,通過正則匹配所有Cookie檔案或者指定域名Cookie真實地址 應該使用Win7以上的,我Win7沒有問題,可以拿到Cookie地址和其內容,然後進行Cookie轉換

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
 
namespace CookieTest
{
    public class FileComm
    {
        /// <summary>
        /// Internet臨時檔案路徑
        /// </summary>
        string cookieUrl;
        public FileComm()
        {
            //Internet臨時檔案路徑
            cookieUrl = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
        }
        //用來把 FileTime時間格式轉化成c#中的string型別,以便我們進一步操作。
        //主體程式如下:
        #region 引入dll
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct INTERNET_CACHE_ENTRY_INFO
        {
            public int dwStructSize;
            public IntPtr lpszSourceUrlName;
            public IntPtr lpszLocalFileName;
            public int CacheEntryType;
            public int dwUseCount;
            public int dwHitRate;
            public int dwSizeLow;
            public int dwSizeHigh;
            public FILETIME LastModifiedTime;
            public FILETIME ExpireTime;
            public FILETIME LastAccessTime;
            public FILETIME LastSyncTime;
            public IntPtr lpHeaderInfo;
            public int dwHeaderInfoSize;
            public IntPtr lpszFileExtension;
            public int dwExemptDelta;
        }
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct SYSTEMTIME
        {
            public short wYear;
            public short wMonth;
            public short wDayOfWeek;
            public short wDay;
            public short wHour;
            public short wMinute;
            public short wSecond;
            public short wMilliseconds;
        }
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern int FileTimeToSystemTime(
        IntPtr lpFileTime,
        IntPtr lpSystemTime);
        [DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr FindFirstUrlCacheEntry(
        [MarshalAs(UnmanagedType.LPTStr)] string lpszUrlSearchPattern,
        IntPtr lpFirstCacheEntryInfo,
        ref int lpdwFirstCacheEntryInfoBufferSize);
        [DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern bool FindNextUrlCacheEntry(
        IntPtr hEnumHandle,
        IntPtr lpNextCacheEntryInfo,
        ref int lpdwNextCacheEntryInfoBufferSize);
        [DllImport("wininet.dll")]
        public static extern bool FindCloseUrlCache(
        IntPtr hEnumHandle);
        const int ERROR_NO_MORE_ITEMS = 259;
        #endregion
        #region FileTimeToSystemTime
        private string FILETIMEtoDataTime(FILETIME time)
        {
            IntPtr filetime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FILETIME)));
            IntPtr systime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SYSTEMTIME)));
            Marshal.StructureToPtr(time, filetime, true);
            FileTimeToSystemTime(filetime, systime);
            SYSTEMTIME st = (SYSTEMTIME)Marshal.PtrToStructure(systime, typeof(SYSTEMTIME));
            string Time = st.wYear.ToString() + "." + st.wMonth.ToString() + "." + st.wDay.ToString() + "." + st.wHour.ToString() + "." + st.wMinute.ToString() + "." + st.wSecond.ToString();
            return Time;
        }
        #endregion
        /// <summary>
        /// 獲取臨時檔案
        /// </summary>
        /// <param name="url">檔案目錄</param>
        /// <param name="regex">篩選正則(臨時檔名)</param>
        /// <returns>鍵為臨時檔名,值為實際檔案地址</returns>
        public Dictionary<string, string> GetFiles(string url, Regex regex = null)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            int nNeeded = 0, nBufSize;
            IntPtr buf;
            INTERNET_CACHE_ENTRY_INFO CacheItem;
            IntPtr hEnum;
            bool r;
            FindFirstUrlCacheEntry(url, IntPtr.Zero, ref nNeeded);
            if (Marshal.GetLastWin32Error() == ERROR_NO_MORE_ITEMS)
                return dic;
            nBufSize = nNeeded;
            buf = Marshal.AllocHGlobal(nBufSize);
            hEnum = FindFirstUrlCacheEntry(null, buf, ref nNeeded);
            while (true)
            {
                CacheItem = (INTERNET_CACHE_ENTRY_INFO)Marshal.PtrToStructure(buf,
                typeof(INTERNET_CACHE_ENTRY_INFO));
                string modifiedTime = FILETIMEtoDataTime(CacheItem.LastModifiedTime);
                string expireTime = FILETIMEtoDataTime(CacheItem.ExpireTime);
                string accessTime = FILETIMEtoDataTime(CacheItem.LastAccessTime);
                string syncTime = FILETIMEtoDataTime(CacheItem.LastSyncTime);
                #region 獲得資料,存入資料庫
                try
                {
                    //此處遍歷CacheItem即可
                    //例如
                    string sname = Marshal.PtrToStringAuto(CacheItem.lpszSourceUrlName); //蛇皮名稱,不知道怎麼說,非檔案實際名稱
                    string w = Marshal.PtrToStringAuto(CacheItem.lpszLocalFileName);//真實檔案地址
                    if (regex == null)
                    {
                        dic[sname] = w;
                    }
                    else if (regex.IsMatch(sname))
                    {
                        dic[sname] = w;
                    }
                }
                catch
                {
                    //異常處理
                }
                #endregion
                string s = Marshal.PtrToStringAuto(CacheItem.lpszSourceUrlName);
                nNeeded = nBufSize;
                r = FindNextUrlCacheEntry(hEnum, buf, ref nNeeded);
                if (!r && Marshal.GetLastWin32Error() == ERROR_NO_MORE_ITEMS)
                    break;
                if (!r && nNeeded > nBufSize)
                {
                    nBufSize = nNeeded;
                    buf = Marshal.ReAllocHGlobal(buf, (IntPtr)nBufSize);
                    FindNextUrlCacheEntry(hEnum, buf, ref nNeeded);
                }
            }
            Marshal.FreeHGlobal(buf);
            return dic;
        }
 
        /// <summary>
        /// 獲取指定域名的Cookie檔案
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public Dictionary<string, string> GetCookieFile(string url = null)
        {
            //預設獲取所有Cookie檔案
            Regex r = new Regex("^Cookie:
[email protected]
");             if (url != null)             {                 r = new Regex("^Cookie:[email protected]" + url + "/$");             }             return GetFiles(cookieUrl, r);         }     } }