1. 程式人生 > >C#從IE緩存讀取圖片

C#從IE緩存讀取圖片

code write 打開 ole rgs internet sdn tex rto

如果用HttpWebRequest和HttpWebResponse從服務器取圖片,會觸發圖片變化。於是想到從IE緩存讀取圖片

參考https://www.cnblogs.com/yelaiju/archive/2010/10/01/1839860.html和https://blog.csdn.net/annkie/article/details/6065521和http://www.mamicode.com/info-detail-370382.html

代碼如下:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Common { class Program {//從IE緩存復制圖片到D盤 static void Main(string[] args) { System.Diagnostics.Process.Start(" http://www.baidu.com "); System.Threading.Thread.Sleep(
2000); //打開IE緩存目錄 Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)); IECache i = new IECache(); //在網頁上找到百度logo圖片的url寫在下面 string b = i.GetPathForCachedFile("https://www.baidu.com/img/bd_logo1.png"); Console.WriteLine(b);
//從緩存中將bd_logo1.png拷貝到D盤下 File.Copy(b, @"d:\bd_logo1.png", true); Console.WriteLine("現在打開D盤目錄看看bd_logo1.png吧"); Console.ReadKey(); } public class IECache { [DllImport("Wininet.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern Boolean GetUrlCacheEntryInfo(String lpxaUrlName, IntPtr lpCacheEntryInfo, ref int lpdwCacheEntryInfoBufferSize); const int ERROR_FILE_NOT_FOUND = 0x2; struct LPINTERNET_CACHE_ENTRY_INFO { public int dwStructSize; IntPtr lpszSourceUrlName; public IntPtr lpszLocalFileName; // int CacheEntryType; // int dwUseCount; // int dwHitRate; //int dwSizeLow; // int dwSizeHigh; //System.Runtime.InteropServices.ComTypes.FILETIME LastModifiedTime; //System.Runtime.InteropServices.ComTypes.FILETIME Expiretime; // System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime; //System.Runtime.InteropServices.ComTypes.FILETIME LastSyncTime; //IntPtr lpHeaderInfo; //readonly int dwheaderInfoSize; //IntPtr lpszFileExtension; //int dwEemptDelta; } // 返回 指定URL文件的緩存在本地文件系統中的路徑 public string GetPathForCachedFile(string fileUrl) { int cacheEntryInfoBufferSize = 0; IntPtr cacheEntryInfoBuffer = IntPtr.Zero; int lastError; Boolean result; try { result = GetUrlCacheEntryInfo(fileUrl, IntPtr.Zero, ref cacheEntryInfoBufferSize); lastError = Marshal.GetLastWin32Error(); if (result == false) { if (lastError == ERROR_FILE_NOT_FOUND) return null; } cacheEntryInfoBuffer = Marshal.AllocHGlobal(cacheEntryInfoBufferSize); result = GetUrlCacheEntryInfo(fileUrl, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSize); lastError = Marshal.GetLastWin32Error(); if (result == true) { Object strObj = Marshal.PtrToStructure(cacheEntryInfoBuffer, typeof(LPINTERNET_CACHE_ENTRY_INFO)); LPINTERNET_CACHE_ENTRY_INFO internetCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO)strObj; String localFileName = Marshal.PtrToStringAuto(internetCacheEntry.lpszLocalFileName); return localFileName; } else return null;// file not found } finally { if (!cacheEntryInfoBuffer.Equals(IntPtr.Zero)) Marshal.FreeHGlobal(cacheEntryInfoBuffer); } } } } }

C#從IE緩存讀取圖片