| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1137 人关注过本帖
标题:快速搜索磁盘文件
只看楼主 加入收藏
qq2889577966
Rank: 4
等 级:业余侠客
威 望:5
帖 子:68
专家分:287
注 册:2021-4-14
结帖率:100%
收藏
 问题点数:0 回复次数:0 
快速搜索磁盘文件
程序编译时,设置为管理员模式,不会的百度。
为方便查看,不写窗口,为动态建立组件,直接粘贴到cs文件中就可以了。
查找文件超快,原理是读取USN Journal,查百度。
只适应NTFS磁盘格式,不能用于FAT32,好像FAT32也没几个在用了吧
程序代码:
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Windows.Forms;

namespace Fast_Search
{
    public partial class Form1 : Form
    {
        private TextBox Input_Direct, Input_FileName;
        private RichTextBox Rich_Results;

        public Form1()
        {
            InitializeComponent();
            // 输入查找目录
            Input_Direct = new TextBox()
            {
                Size = new Size(200, 20),
                Location = new Point(5, 5),
                Text = @"C:"
            };
            this.Controls.Add(Input_Direct);

            Label label_dir = new Label()
            {
                AutoSize = true,
                Location = new Point(210,10),
                Text = "(输入目录)",
            };
            this.Controls.Add(label_dir);

            // 输入查找文件
            Input_FileName = new TextBox()
            {
                Size = new Size(200, 20),
                Location = new Point(280, 5),
                Text = @".exe"
            };
            this.Controls.Add(Input_FileName);

            Label label_file= new Label()
            {
                AutoSize = true,
                Location = new Point(485, 10),
                Text = "(输入文件)",
            };
            this.Controls.Add(label_file);

            // 查询按钮
            Button Button_Search = new Button()
            {
                Size = new Size(100,20),
                Location = new Point(560,5),
                Text = "查找"
            };
            Button_Search.Click += Button_Search_Click;
            this.Controls.Add(Button_Search);

            // 查询结果显示
            Rich_Results = new RichTextBox()
            {
                Size = new Size(400, 300),
                Location = new Point(5, 30)
            };
            this.Controls.Add(Rich_Results);
        }

        private void Button_Search_Click(object sender, EventArgs e)
        {
            DriveInfo driveInfo = new DriveInfo(Input_Direct.Text);
            var tmp = DriveInfoExtension.EnumerateFiles(driveInfo).ToList();

            var tmp1 = tmp.Where(x => x.Contains(Input_FileName.Text)).ToList();
            Rich_Results.Clear();
            for (int i = 0; i < tmp1.Count(); i++)
            {
                Rich_Results.AppendText(tmp1[i] + "\r");
            }
        }
    }

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

    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 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;
        }

        [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)
        {
            m_DriveLetter = szDriveLetter;
            IntPtr 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)
            {
                CloseHandle(m_hCJ);
                m_hCJ = INVALID_HANDLE_VALUE;
            }

            if (m_Buffer != IntPtr.Zero)
            {
                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;

                if (m_Buffer.ToInt32() != 0)
                {
                    throw new Exception("invalid buffer");
                }

                m_BufferSize = 65536;
                m_Buffer = Marshal.AllocHGlobal(m_BufferSize);
                szDriveLetter = szDriveLetter.TrimEnd('\\');
                m_hCJ = OpenVolume(szDriveLetter);

                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 = 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;
                        IntPtr pUsnRecord = new IntPtr(m_Buffer.ToInt32() + 8);

                        while ((dwRetBytes > 8))
                        {
                            usnRecord = (USN_RECORD)Marshal.PtrToStructure(pUsnRecord, usnRecord.GetType());
                            string FileName = Marshal.PtrToStringUni(new IntPtr(pUsnRecord.ToInt32() + usnRecord.FileNameOffset), usnRecord.FileNameLength / 2);
                            bIsFile = !usnRecord.FileAttributes.HasFlag(FileAttributes.Directory);
                            dicFRNLookup.Add(usnRecord.FileReferenceNumber, new FSNode(usnRecord.FileReferenceNumber, usnRecord.ParentFileReferenceNumber, FileName, bIsFile));
                            pUsnRecord = new IntPtr(pUsnRecord.ToInt32() + usnRecord.RecordLength);
                            dwRetBytes -= usnRecord.RecordLength;
                        }
                        mft.StartFileReferenceNumber = Marshal.ReadInt64(m_Buffer, 0);
                    }
                    else
                    {
                        break;
                    }

                } while (!(cb <= 8));

                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();
            }
        }

        public static bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
    }

}




[此贴子已经被作者于2021-8-10 11:47编辑过]

搜索更多相关主题的帖子: private public IntPtr int new 
2021-08-10 09:45
快速回复:快速搜索磁盘文件
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.060737 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved