c# 一个删除垃圾文件处理的类

本文介绍了一种用于清除Windows系统中Internet缓存、回收站及recent与temp文件夹内临时文件的方法。通过调用WinAPI,实现对指定文件与缓存的有效删除,有助于释放磁盘空间并提高系统运行效率。
  1. usingSystem;
  2. usingSystem.Runtime.InteropServices;
  3. usingSystem.IO;
  4. namespaceWinAssistant
  5. {
  6. //Classfordeletingtherubbish.
  7. classDelRubbish
  8. {
  9. #region清空临时InternetCache
  10. //ForPInvoke:ContainsinformationaboutanentryintheInternetcache
  11. [StructLayout(LayoutKind.Explicit,Size=80)]
  12. publicstructINTERNET_CACHE_ENTRY_INFOA
  13. {
  14. [FieldOffset(0)]
  15. publicuintdwStructSize;
  16. [FieldOffset(4)]
  17. publicIntPtrlpszSourceUrlName;
  18. [FieldOffset(8)]
  19. publicIntPtrlpszLocalFileName;
  20. [FieldOffset(12)]
  21. publicuintCacheEntryType;
  22. [FieldOffset(16)]
  23. publicuintdwUseCount;
  24. [FieldOffset(20)]
  25. publicuintdwHitRate;
  26. [FieldOffset(24)]
  27. publicuintdwSizeLow;
  28. [FieldOffset(28)]
  29. publicuintdwSizeHigh;
  30. [FieldOffset(32)]
  31. publicFILETIMELastModifiedTime;
  32. [FieldOffset(40)]
  33. publicFILETIMEExpireTime;
  34. [FieldOffset(48)]
  35. publicFILETIMELastAccessTime;
  36. [FieldOffset(56)]
  37. publicFILETIMELastSyncTime;
  38. [FieldOffset(64)]
  39. publicIntPtrlpHeaderInfo;
  40. [FieldOffset(68)]
  41. publicuintdwHeaderInfoSize;
  42. [FieldOffset(72)]
  43. publicIntPtrlpszFileExtension;
  44. [FieldOffset(76)]
  45. publicuintdwReserved;
  46. [FieldOffset(76)]
  47. publicuintdwExemptDelta;
  48. }
  49. #regionDllimport
  50. //ForPInvoke:InitiatestheenumerationofthecachegroupsintheInternetcache
  51. [DllImport(@"wininet",
  52. SetLastError=true,
  53. CharSet=CharSet.Auto,
  54. EntryPoint="FindFirstUrlCacheGroup",
  55. CallingConvention=CallingConvention.StdCall)]
  56. privatestaticexternIntPtrFindFirstUrlCacheGroup(
  57. intdwFlags,
  58. intdwFilter,
  59. IntPtrlpSearchCondition,
  60. intdwSearchCondition,
  61. reflonglpGroupId,
  62. IntPtrlpReserved);
  63. //ForPInvoke:Retrievesthenextcachegroupinacachegroupenumeration
  64. [DllImport(@"wininet",
  65. SetLastError=true,
  66. CharSet=CharSet.Auto,
  67. EntryPoint="FindNextUrlCacheGroup",
  68. CallingConvention=CallingConvention.StdCall)]
  69. privatestaticexternboolFindNextUrlCacheGroup(
  70. IntPtrhFind,
  71. reflonglpGroupId,
  72. IntPtrlpReserved);
  73. //ForPInvoke:ReleasesthespecifiedGROUPIDandanyassociatedstateinthecacheindexfile
  74. [DllImport(@"wininet",
  75. SetLastError=true,
  76. CharSet=CharSet.Auto,
  77. EntryPoint="DeleteUrlCacheGroup",
  78. CallingConvention=CallingConvention.StdCall)]
  79. privatestaticexternboolDeleteUrlCacheGroup(
  80. longGroupId,
  81. intdwFlags,
  82. IntPtrlpReserved);
  83. //ForPInvoke:BeginstheenumerationoftheInternetcache
  84. [DllImport(@"wininet",
  85. SetLastError=true,
  86. CharSet=CharSet.Auto,
  87. EntryPoint="FindFirstUrlCacheEntryA",
  88. CallingConvention=CallingConvention.StdCall)]
  89. privatestaticexternIntPtrFindFirstUrlCacheEntry(
  90. [MarshalAs(UnmanagedType.LPTStr)]stringlpszUrlSearchPattern,
  91. IntPtrlpFirstCacheEntryInfo,
  92. refintlpdwFirstCacheEntryInfoBufferSize);
  93. //ForPInvoke:RetrievesthenextentryintheInternetcache
  94. [DllImport(@"wininet",
  95. SetLastError=true,
  96. CharSet=CharSet.Auto,
  97. EntryPoint="FindNextUrlCacheEntryA",
  98. CallingConvention=CallingConvention.StdCall)]
  99. privatestaticexternboolFindNextUrlCacheEntry(
  100. IntPtrhFind,
  101. IntPtrlpNextCacheEntryInfo,
  102. refintlpdwNextCacheEntryInfoBufferSize);
  103. //ForPInvoke:Removesthefilethatisassociatedwiththesourcenamefromthecache,ifthefileexists
  104. [DllImport(@"wininet",
  105. SetLastError=true,
  106. CharSet=CharSet.Auto,
  107. EntryPoint="DeleteUrlCacheEntryA",
  108. CallingConvention=CallingConvention.StdCall)]
  109. privatestaticexternboolDeleteUrlCacheEntry(
  110. IntPtrlpszUrlName);
  111. #endregionDllimport
  112. #regionmethods
  113. publicstaticvoidDeleteNetCache()
  114. {
  115. #regionvariables
  116. //Indicatesthatallofthecachegroupsintheuser'ssystemshouldbeenumerated
  117. constintCACHEGROUP_SEARCH_ALL=0x0;
  118. //Indicatesthatallthecacheentriesthatareassociatedwiththecachegroup
  119. //shouldbedeleted,unlesstheentrybelongstoanothercachegroup.
  120. constintCACHEGROUP_FLAG_FLUSHURL_ONDELETE=0x2;
  121. //Filenotfound.
  122. constintERROR_FILE_NOT_FOUND=0x2;
  123. //Nomoreitemshavebeenfound.
  124. constintERROR_NO_MORE_ITEMS=259;
  125. //PointertoaGROUPIDvariable
  126. longgroupId=0;
  127. //Localvariables
  128. intcacheEntryInfoBufferSizeInitial=0;
  129. intcacheEntryInfoBufferSize=0;
  130. IntPtrcacheEntryInfoBuffer=IntPtr.Zero;
  131. INTERNET_CACHE_ENTRY_INFOAinternetCacheEntry;
  132. IntPtrenumHandle=IntPtr.Zero;
  133. boolreturnValue=false;
  134. #endregionvariables
  135. //Deletethegroupsfirst.
  136. //Groupsmaynotalwaysexistonthesystem.
  137. //Formoreinformation,visitthefollowingMicrosoftWebsite:
  138. //http://msdn.microsoft.com/library/?url=/workshop/networking/wininet/overview/cache.asp
  139. //Bydefault,aURLdoesnotbelongtoanygroup.Therefore,thatcachemaybecome
  140. //emptyevenwhentheCacheGroupAPIsarenotusedbecausetheexistingURLdoesnotbelongtoanygroup.
  141. enumHandle=FindFirstUrlCacheGroup(0,CACHEGROUP_SEARCH_ALL,IntPtr.Zero,0,refgroupId,IntPtr.Zero);
  142. //IftherearenoitemsintheCache,youarefinished.
  143. if(enumHandle!=IntPtr.Zero&&ERROR_NO_MORE_ITEMS==Marshal.GetLastWin32Error())
  144. return;
  145. //LoopthroughCacheGroup,andthendeleteentries.
  146. while(true)
  147. {
  148. //DeleteaparticularCacheGroup.
  149. returnValue=DeleteUrlCacheGroup(groupId,CACHEGROUP_FLAG_FLUSHURL_ONDELETE,IntPtr.Zero);
  150. if(!returnValue&&ERROR_FILE_NOT_FOUND==Marshal.GetLastWin32Error())
  151. {
  152. returnValue=FindNextUrlCacheGroup(enumHandle,refgroupId,IntPtr.Zero);
  153. }
  154. if(!returnValue&&(ERROR_NO_MORE_ITEMS==Marshal.GetLastWin32Error()||ERROR_FILE_NOT_FOUND==Marshal.GetLastWin32Error()))
  155. break;
  156. }
  157. //StarttodeleteURLsthatdonotbelongtoanygroup.
  158. enumHandle=FindFirstUrlCacheEntry(null,IntPtr.Zero,refcacheEntryInfoBufferSizeInitial);
  159. if(enumHandle!=IntPtr.Zero&&ERROR_NO_MORE_ITEMS==Marshal.GetLastWin32Error())
  160. return;
  161. cacheEntryInfoBufferSize=cacheEntryInfoBufferSizeInitial;
  162. cacheEntryInfoBuffer=Marshal.AllocHGlobal(cacheEntryInfoBufferSize);
  163. enumHandle=FindFirstUrlCacheEntry(null,cacheEntryInfoBuffer,refcacheEntryInfoBufferSizeInitial);
  164. while(true)
  165. {
  166. internetCacheEntry=(INTERNET_CACHE_ENTRY_INFOA)Marshal.PtrToStructure(cacheEntryInfoBuffer,typeof(INTERNET_CACHE_ENTRY_INFOA));
  167. cacheEntryInfoBufferSizeInitial=cacheEntryInfoBufferSize;
  168. returnValue=DeleteUrlCacheEntry(internetCacheEntry.lpszSourceUrlName);
  169. if(!returnValue)
  170. {
  171. returnValue=FindNextUrlCacheEntry(enumHandle,cacheEntryInfoBuffer,refcacheEntryInfoBufferSizeInitial);
  172. }
  173. if(!returnValue&&ERROR_NO_MORE_ITEMS==Marshal.GetLastWin32Error())
  174. {
  175. break;
  176. }
  177. if(!returnValue&&cacheEntryInfoBufferSizeInitial>cacheEntryInfoBufferSize)
  178. {
  179. cacheEntryInfoBufferSize=cacheEntryInfoBufferSizeInitial;
  180. cacheEntryInfoBuffer=Marshal.ReAllocHGlobal(cacheEntryInfoBuffer,(IntPtr)cacheEntryInfoBufferSize);
  181. returnValue=FindNextUrlCacheEntry(enumHandle,cacheEntryInfoBuffer,refcacheEntryInfoBufferSizeInitial);
  182. }
  183. }
  184. Marshal.FreeHGlobal(cacheEntryInfoBuffer);
  185. }
  186. #endregionmethods
  187. #endregion清空临时Cache
  188. #region清空回收站
  189. [Flags()]
  190. publicenumSHERB
  191. {
  192. SHERB_NOCONFIRMATION=0x00000001,
  193. SHERB_NOPROGRESSUI=0x00000002,
  194. SHERB_NOSOUND=0x00000004
  195. }
  196. [DllImport("shell32.dll",CharSet=CharSet.Auto)]
  197. privatestaticexternuintSHEmptyRecycleBin(
  198. IntPtrhwnd,
  199. stringpszRootPath,
  200. SHERBdwFlags);
  201. publicstaticvoidDeleteRecycle()
  202. {
  203. SHEmptyRecycleBin(IntPtr.Zero,null,SHERB.SHERB_NOCONFIRMATION);
  204. }
  205. #endregion清空回收站
  206. #region清空recent、temp文件夹
  207. publicstaticvoidDeleteFile()
  208. {
  209. stringtemp=Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).ToString().Replace("ApplicationData",null)+"Temp";
  210. stringrecent=Environment.GetFolderPath(Environment.SpecialFolder.Recent).ToString();
  211. CleanUp(temp);
  212. CleanUp(recent);
  213. }
  214. privatestaticvoidCleanUp(stringdir)
  215. {
  216. foreach(stringdinDirectory.GetFileSystemEntries(dir))
  217. {
  218. try
  219. {
  220. if(File.Exists(d))
  221. {
  222. File.Delete(d);
  223. }
  224. else
  225. {
  226. //CleanUp(d);
  227. Directory.Delete(d,true);
  228. }
  229. }
  230. catch{}
  231. }
  232. }
  233. #endregion清空recent、temp文件夹
  234. }
  235. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值