C#快速找出磁盘内的所有文件
本文只针对NTFS格式化的磁盘文件快速检索,速度不是非常快,是让你震惊。
一般用文件遍历的方法检索一个50G的文件夹需要几十分钟甚至一个小时的时间,而用本方法只需几秒。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic; public class MFTScanner
{
private static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
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 = 3;
private const int FILE_READ_ATTRIBUTES = 0x80;
private const int FILE_NAME_IINFORMATION = 9;
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 FileAttribute 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, 0, 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 = 0;
var cb = 0;
var dicFRNLookup = new Dictionary<long, FSNode>();
var bIsFile = false; // This shouldn't be called more than once.
if (m_Buffer.ToInt32() != 0)
{
throw new Exception("invalid buffer");
} // Assign buffer size
m_BufferSize = 65536;
//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)
{
throw new Exception("Couldn't open handle to the volume.");
} mft.StartFileReferenceNumber = 0;
mft.LowUsn = 0;
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() + 8); while ((dwRetBytes > 8))
{
// 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 / 2); bIsFile = !usnRecord.FileAttributes.HasFlag(FileAttribute.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, 0); }
else
{
break; // TODO: might not be correct. Was : Exit Do } } while (!(cb <= 8)); // 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();
}
}
}
调用方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics; namespace ConsoleApplication28
{
class Program
{
static void Main(string[] args)
{
var sw = Stopwatch.StartNew();
var files = EnumerateFiles("f:").ToArray();
var elapsed = sw.ElapsedMilliseconds.ToString();
Console.WriteLine(string.Format("Found {0} files, elapsed {1} ms", files.Length, elapsed));
}
}
}
方法只能传磁盘名
C#快速找出磁盘内的所有文件的更多相关文章
- 如何快速找出Linux中的重复文件
md5sum | sort | uniq -w32 --all-repeated=separate [1]find -not -empty -type f -printf “%s\n” :find是查 ...
- Matlab.NET混合编程技巧之——找出Matlab内置函数
原文:[原创]Matlab.NET混合编程技巧之--找出Matlab内置函数 Matlab与.NET的混合编程,掌握了基本过程,加上一定的开发经验和算法基础,肯定不难.反之,有时候一个小错误,可能抓破 ...
- 【原创】Matlab.NET混合编程技巧之找出Matlab内置函数
本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新 Matlab和C#混合编程文章目录 :[目录]Matlab和C#混合编程文章目录 Matlab与.N ...
- Matlab.NET混编技巧之——找出Matlab内置函数
原文 http://www.cnblogs.com/asxinyu/p/3295309.html Matlab与.NET的混合编程,掌握了基本过程,加上一定的开发经验和算法基础,肯 定不难.反之,有时 ...
- python——快速找出两个电子表中数据的差异
最近刚接触python,找点小任务来练练手,希望自己在实践中不断的锻炼自己解决问题的能力. 公司里会有这样的场景:有一张电子表格的内容由两三个部门或者更多的部门用到,这些员工会在维护这些表格中不定期的 ...
- 快速找出网站中可能存在的XSS漏洞实践
笔者写了一些XSS漏洞的挖掘过程记录下来,方便自己也方便他人. 一.背景 在本篇文章当中会一permeate生态测试系统为例,笔者此前写过一篇文章当中笔者已经讲解如何安装permeate渗透测试系统, ...
- 快速找出网站中可能存在的XSS漏洞实践(一)
一.背景 笔者最近在慕课录制了一套XSS跨站漏洞 加强Web安全视频教程,课程当中有讲到XSS的挖掘方式,所以在录制课程之前需要做大量实践案例,最近视频已经录制完成,准备将这些XSS漏洞的挖掘过程记录 ...
- 快速找出故障机器(single number)
简单起见,假设每个机器存储一个标号为ID的记录(ID是小于十亿的整数),假设每份数据都保存两个备份,这样就有两个机器储存了同样的数据. 1.在某个时间,如果得到一个数据文件ID的列表,是否能够快速地找 ...
- 编程之美 set 12 快速找出故障机器
题目 1. 所有的 ID 都出现 2 次, 只有一个例外, 找到那个例外的 ID 2. 所有的 ID 都出现两次, 只有两个例外, 找出例外的那两个 总计 1. 剑指 offer 上有这两道题的解法, ...
随机推荐
- 第11月第18天 RACSequence
1. RACSequence的内部存储结构就像一个单链表,有两个指针head和tail,head指针指向了当前链表的第一个元素,tail指向head指针下一个元素:根据RACSequence是否还有内 ...
- bzoj3029 守卫者的挑战 (多维dp)
题面: 打开了黑魔法师Vani的大门,队员们在迷宫般的路上漫无目的地搜寻着关押applepi的监狱的所在地.突然,眼前一道亮光闪过."我,Nizem,是黑魔法圣殿的守卫者.如果你能通过我的挑 ...
- 关于python开发CRM系统
注意本项目是针对培训学校开发简化的CRM CRM简介 CRM全称:customer relationship management 无CRM的痛点 没有CMR的缺点及痛点: 每个销售会通过Excel来 ...
- [Alg::DP] Square Subsequence
题目如下: #include <iostream> #include <string> #include <vector> using namespace std; ...
- LeetCode(Easy)--C++笔记
前言:这是关于LeetCode上面练习题C++的笔记,有些地方参考有网友的解题方法(可能有些参考没能注明,望谅解),如有需要改进的地方希望留言指教,多谢! 目录: ZigZag Conversion ...
- c#按字符串中的数字排序问题
在.net 的framewrok框架中提供的排序方法中,如string.sort() 或ArrayList.Sort()方法.这两个方法对字符串排序时,如果字符串中含有数字,则不会按数字大小排序.如: ...
- 002_CentOS-6.4-x86_64安装包的说明
http://mirrors.sohu.com/centos/6.6/isos/x86_64/?qq-pf-to=pcqq.group //souhu镜像下载地址 0_README.txt 25-Oc ...
- bootstrap 引用注意事项
2014年6月8日 13:35:31 bootstrap 提供了cdn服务,在引用css,js的时候注意先后顺序,firebug就不会报错 <script src="http://cd ...
- 自定义Web组件
一.Session 1.面向对象基础 面向对象中通过索引的方式访问对象,需要内部实现 __getitem__ .__delitem__.__setitem__方法 +? 1 2 3 4 5 6 7 8 ...
- 最长回文子串—Manacher 算法 及 python实现
最长回文子串问题:给定一个字符串,求它的最长回文子串长度.如果一个字符串正着读和反着读是一样的,那它就是回文串. 给定一个字符串,求它最长的回文子串长度,例如输入字符串'35534321',它的最 ...