当前位置: 首页 > 编程语言 > C#

如何在C#中使用CreateFile打开一个目录来检查删除的条目?分享

时间:2023-04-11 03:02:56 C#

C#中如何使用CreateFile打开一个目录检查是否有删除项?如何在C#中使用CreateFile打开目录以检查已删除文件的条目?还是现在不可能?我记得当时能够使用CreateFile或可能的CreateFileEx打开NTFS分区上的目录,但在较旧的操作系统下使用C++。到目前为止,我已经有足够的WindowsAPI调用(对kernel32.dll)来读取现有文件,但它不会打开目录:usingSystem;使用System.Collections.Generic;使用系统文本;使用System.IO使用System.Runtime.InteropServices;使用System.Security.Permissions;使用System.Runtime.ConstrainedExecution;使用系统安全;namespaceKernel_Test{classProgram{staticvoidMain(string[]args){Kernel_ToolscKT=newKernel_Tools();cKT.DoTest("C:\Temp");cKT.DoTest("C:\Temp\test.txt");}}[SecurityPermission(SecurityAction.InheritanceDemand,UnmanagedCode=true)][SecurityPermission(SecurityAction.Demand,UnmanagedCode=true)]classKernel_Tools{publicvoidDoTest(stringcTarget){IntPtrcFile=NativeMethods.CreateFile(cTarget,NativeMethods.GENERIC_READ/*0或NativeMethods.GENERIC_READ*/,FilePtrRead..Zero/*尝试失败:NativeMethods.OPEN_ALWAYS*/,(FileMode)NativeMethods.OPEN_EXISTING,NativeMethods.FILE_FLAG_BACKUP_SEMANTICS/*0*/,IntPtr.Zero);控制台.WriteLine(cTarget);控制台.WriteLine(cFile);如果((int)cFile!=-1){int长度=20;byte[]bytes=newbyte[length];intnumRead=0;intErrorCheck=NativeMethods.ReadFile(cFile,bytes,length,outnumRead,IntPtr.Zero);//此示例代码不适用于所有文件。//intr=NativeMethods.ReadFile(_handle,bytes,length,outnumRead,IntPtr.Zero);//因为我们删除了MyFileReader的终结器,我们不再需要在这里调用GC.KeepAlive。平台调用将使SafeHandle//实例在调用期间保持活动状态。if(ErrorCheck==0){Console.WriteLine("读取失败。");NativeMethods.CloseHandle(cFile);返回;//抛出新的Win32Exception(Marshal.GetLastWin32Error());}if(numRead