C#从IE缓存读取图片
如果用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); } } } } }