相信使用过Everything的人都对其超快的搜索速度印象非常深刻,它的主要原理是通过扫描NTFS磁盘的USN Journal读取的文件列表,而不是磁盘目录,由于USN Journal非常小,因此能实现快速搜索。在CodePlex上也有人对这个功能进行了.Net的封装:MFT Scanner in VB.NET

由于.Net程序的Dll基本上是通用的,在C#中也可以直接使用它。今天发现了有人将其翻译成了C#的版本《使用MFT Scanner遍巡USN Journal,快速找出磁碟內的所有檔案》,使用起来更为方便了。不过,原文貌似有点Bug,编译不过去,这里我改了一下,附录如下:

     public class MFTScanner
{
private static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-);
private const uint GENERIC_READ = 0x80000000;
private const int FILE_SHARE_READ = 0x1;
private const int FILE_SHARE_WRITE = 0x2;
private const int OPEN_EXISTING = ;
private const int FILE_READ_ATTRIBUTES = 0x80;
private const int FILE_NAME_IINFORMATION = ;
private const int FILE_FLAG_BACKUP_SEMANTICS = 0x2000000;
private const int FILE_OPEN_FOR_BACKUP_INTENT = 0x4000;
private const int FILE_OPEN_BY_FILE_ID = 0x2000;
private const int FILE_OPEN = 0x1;
private const int OBJ_CASE_INSENSITIVE = 0x40;
private const int FSCTL_ENUM_USN_DATA = 0x900b3; [StructLayout(LayoutKind.Sequential)]
private struct MFT_ENUM_DATA
{
public long StartFileReferenceNumber;
public long LowUsn;
public long HighUsn;
} [StructLayout(LayoutKind.Sequential)]
private struct USN_RECORD
{
public int RecordLength;
public short MajorVersion;
public short MinorVersion;
public long FileReferenceNumber;
public long ParentFileReferenceNumber;
public long Usn;
public long TimeStamp;
public int Reason;
public int SourceInfo;
public int SecurityId;
public FileAttributes FileAttributes;
public short FileNameLength;
public short FileNameOffset;
} [StructLayout(LayoutKind.Sequential)]
private struct IO_STATUS_BLOCK
{
public int Status;
public int Information;
} [StructLayout(LayoutKind.Sequential)]
private struct UNICODE_STRING
{
public short Length;
public short MaximumLength;
public IntPtr Buffer;
} [StructLayout(LayoutKind.Sequential)]
private struct OBJECT_ATTRIBUTES
{
public int Length;
public IntPtr RootDirectory;
public IntPtr ObjectName;
public int Attributes;
public int SecurityDescriptor;
public int SecurityQualityOfService;
} //// MFT_ENUM_DATA
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool DeviceIoControl(IntPtr hDevice, int dwIoControlCode, ref MFT_ENUM_DATA lpInBuffer, int nInBufferSize, IntPtr lpOutBuffer, int nOutBufferSize, ref int lpBytesReturned, IntPtr lpOverlapped); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode, IntPtr lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern Int32 CloseHandle(IntPtr lpObject); [DllImport("ntdll.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern int NtCreateFile(ref IntPtr FileHandle, int DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes, ref IO_STATUS_BLOCK IoStatusBlock, int AllocationSize, int FileAttribs, int SharedAccess, int CreationDisposition, int CreateOptions, int EaBuffer,
int EaLength); [DllImport("ntdll.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern int NtQueryInformationFile(IntPtr FileHandle, ref IO_STATUS_BLOCK IoStatusBlock, IntPtr FileInformation, int Length, int FileInformationClass); private IntPtr m_hCJ;
private IntPtr m_Buffer;
private int m_BufferSize; private string m_DriveLetter; private class FSNode
{
public long FRN;
public long ParentFRN;
public string FileName; public bool IsFile;
public FSNode(long lFRN, long lParentFSN, string sFileName, bool bIsFile)
{
FRN = lFRN;
ParentFRN = lParentFSN;
FileName = sFileName;
IsFile = bIsFile;
}
} private IntPtr OpenVolume(string szDriveLetter)
{ IntPtr hCJ = default(IntPtr);
//// volume handle m_DriveLetter = szDriveLetter;
hCJ = CreateFile(@"\\.\" + szDriveLetter, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, , IntPtr.Zero); return hCJ; } private void Cleanup()
{
if (m_hCJ != IntPtr.Zero)
{
// Close the volume handle.
CloseHandle(m_hCJ);
m_hCJ = INVALID_HANDLE_VALUE;
} if (m_Buffer != IntPtr.Zero)
{
// Free the allocated memory
Marshal.FreeHGlobal(m_Buffer);
m_Buffer = IntPtr.Zero;
} } public IEnumerable<String> EnumerateFiles(string szDriveLetter)
{
try
{
var usnRecord = default(USN_RECORD);
var mft = default(MFT_ENUM_DATA);
var dwRetBytes = ;
var cb = ;
var dicFRNLookup = new Dictionary<long, FSNode>();
var bIsFile = false; // This shouldn't be called more than once.
if (m_Buffer.ToInt32() != )
{
throw new Exception("invalid buffer");
} // Assign buffer size
m_BufferSize = ;
//64KB // Allocate a buffer to use for reading records.
m_Buffer = Marshal.AllocHGlobal(m_BufferSize); // correct path
szDriveLetter = szDriveLetter.TrimEnd('\\'); // Open the volume handle
m_hCJ = OpenVolume(szDriveLetter); // Check if the volume handle is valid.
if (m_hCJ == INVALID_HANDLE_VALUE)
{
string errorMsg = "Couldn't open handle to the volume.";
if (!IsAdministrator())
errorMsg += "Current user is not administrator"; throw new Exception(errorMsg);
} mft.StartFileReferenceNumber = ;
mft.LowUsn = ;
mft.HighUsn = long.MaxValue; do
{
if (DeviceIoControl(m_hCJ, FSCTL_ENUM_USN_DATA, ref mft, Marshal.SizeOf(mft), m_Buffer, m_BufferSize, ref dwRetBytes, IntPtr.Zero))
{
cb = dwRetBytes;
// Pointer to the first record
IntPtr pUsnRecord = new IntPtr(m_Buffer.ToInt32() + ); while ((dwRetBytes > ))
{
// Copy pointer to USN_RECORD structure.
usnRecord = (USN_RECORD)Marshal.PtrToStructure(pUsnRecord, usnRecord.GetType()); // The filename within the USN_RECORD.
string FileName = Marshal.PtrToStringUni(new IntPtr(pUsnRecord.ToInt32() + usnRecord.FileNameOffset), usnRecord.FileNameLength / ); bIsFile = !usnRecord.FileAttributes.HasFlag(FileAttributes.Directory);
dicFRNLookup.Add(usnRecord.FileReferenceNumber, new FSNode(usnRecord.FileReferenceNumber, usnRecord.ParentFileReferenceNumber, FileName, bIsFile)); // Pointer to the next record in the buffer.
pUsnRecord = new IntPtr(pUsnRecord.ToInt32() + usnRecord.RecordLength); dwRetBytes -= usnRecord.RecordLength;
} // The first 8 bytes is always the start of the next USN.
mft.StartFileReferenceNumber = Marshal.ReadInt64(m_Buffer, ); }
else
{
break; // TODO: might not be correct. Was : Exit Do } } while (!(cb <= )); // Resolve all paths for Files
foreach (FSNode oFSNode in dicFRNLookup.Values.Where(o => o.IsFile))
{
string sFullPath = oFSNode.FileName;
FSNode oParentFSNode = oFSNode; while (dicFRNLookup.TryGetValue(oParentFSNode.ParentFRN, out oParentFSNode))
{
sFullPath = string.Concat(oParentFSNode.FileName, @"\", sFullPath);
}
sFullPath = string.Concat(szDriveLetter, @"\", sFullPath); yield return sFullPath;
}
}
finally
{
//// cleanup
Cleanup();
}
} public static bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}

原文还提供了一个扩展方法,方便我们获取某个磁盘下的所有的文件名。

     public static class DriveInfoExtension
{
public static IEnumerable<String> EnumerateFiles(this DriveInfo drive)
{
return (new MFTScanner()).EnumerateFiles(drive.Name);
}
}

需要注意的是,读取USN Journal是需要管理员权限的,因此使用这个类需要管理员权限才能正常运行。

另外,这个类封装的也略为简单,只读取了文件名,实际上还可以读取文件大小,属性等常用信息,修改一下代码非常容易获取这些属性。通过它们可以非常方便写出一些分析磁盘空间占用的程序,这里就不举例了。

在C#中快速查询文件的更多相关文章

  1. linux中快速清空文件内容的几种方法

    这篇文章主要介绍了linux中快速清空文件内容的几种方法,需要的朋友可以参考下 $ : > filename $ > filename $ echo "" > f ...

  2. 在project窗口中快速定位文件

    [在project窗口中快速定位文件] 点击带圆圈的小叉叉按钮,这个时候Project中就会定位到当前文件目录下了. 参考:http://blog.csdn.net/hyr83960944/artic ...

  3. linux中快速查找文件

    在使用linux时,经常需要进行文件查找.其中查找的命令主要有find和grep.两个命令是有区的. 区别:(1)find命令是根据文件的属性进行查找,如文件名,文件大小,所有者,所属组,是否为空,访 ...

  4. Oracle中快速查询和操作某个用户下的所有表数据信息

    一.禁止所有的外键约束 在pl/sql developer下执行如下语句:SELECT 'ALTER TABLE ' || table_name || ' disable CONSTRAINT ' | ...

  5. 在VS中快速查看文件被谁签出

    步骤如下: 1 在VS中的菜单上单击鼠标右键,然后选择显示“源代码管理” 2 选中要查看的文件后,在源代码管理中单击“属性” 3 打开第2个标签页“Check Out Status”,可以看到签出人等 ...

  6. java中过滤查询文件

    需求,过滤出C盘demo目录下 所有以.java的文件不区分大小写 通过实现FileFilter接口 定义过滤规则,然后将这个实现类对象传给ListFiles方法作为参数即可. 使用递归方法实现 pa ...

  7. DELPHI 数据集在内存中快速查询方法

    1.Bookmark var p:pointer; procedure TForm1.Button1Click(Sender: TObject);//加个标签 begin   p:=cxGrid1DB ...

  8. linux快速清空文件 比如log日志

    linux中快速清空文件内容的几种方法这篇文章主要介绍了linux中快速清空文件内容的几种方法,需要的朋友可以参考下 权限要求: 至少执行用户对该文件有写的权限 --w------- 1 QA_Dep ...

  9. 用DOM解析XML ,用xpath快速查询XML节点

    XPath是一种快速查询xml节点和属性的一种语言,Xpath和xml的关系就像是sql语句和数据库的关系.用sql语句可以从数据库中快速查询出东西同样的用xPath也可以快速的从xml中查询出东西. ...

随机推荐

  1. JS模块化工具requirejs教程02

    基本API require会定义三个变量:define,require,requirejs,其中require === requirejs,一般使用require更简短 define 从名字就可以看出 ...

  2. 【CF24D】Broken Robot (DP+高斯消元)

    题目链接 题意:给定一个\(n\times m\)的矩阵,每次可以向→↓←移动一格,也可以原地不动,求从\((x,y)\)到最后一行的期望步数. 此题标签\(DP\) 看到上面这个肯定会想到 方法一: ...

  3. Python学习笔记 - day6 - 函数

    函数 函数在编程语言中就是完成特定功能的一个词句组(代码块),这组语句可以作为一个单位使用,并且给它取一个名字.可以通过函数名在程序的不同地方多次执行(这叫函数的调用).函数在编程语言中有基本分为:预 ...

  4. linux USB HOST之EHCI和OHCI【转】

    转自:http://blog.csdn.net/ljzcom/article/details/8186914 版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[-] 2 关键数据结 ...

  5. hdu 1513(滚动数组)

    Palindrome Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total ...

  6. [BZOJ3698] XWW的难题 网络流

    3698: XWW的难题 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 533  Solved: 275[Submit][Status][Discus ...

  7. 【互动问答分享】第11期决胜云计算大数据时代Spark亚太研究院公益大讲堂

    Q1:docker成熟度如何? Docker是2013年和2014年最火爆的云计算开源项目: Baidu公司是中国使用Docker最为深入和最大规模的公司,线上稳定运行数十万个Docker容器,目前已 ...

  8. POJ 2255 Tree Recovery && Ulm Local 1997 Tree Recovery (二叉树的前中后序遍历)

    链接:poj.org/problem?id=2255 本文链接:http://www.cnblogs.com/Ash-ly/p/5463375.html 题意: 分别给你一个二叉树的前序遍历序列和中序 ...

  9. 洛谷P1095 绝地武士的逃离

    好吧原题是守望者的逃离,我强行改了一波题面,因为信仰=-=(? May the force be with us. 绝地跑步速度为17m/s,但无法逃离荒岛.绝地的原力恢复速度为4点/s,只有处在原地 ...

  10. Linux命令之quota

    quota [-guqvswim] [-l | [-Q | -A] ] [-F quotaformat] quota [-qvswim] [-l | [-Q | -A]] [-F quotaforma ...