栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

是否有更快的方法来在.NET中递归浏览目录?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

是否有更快的方法来在.NET中递归浏览目录?

需要一点调整的此实现要快5到10倍。

    static List<Info> RecursiveScan2(string directory) {        IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);        WIN32_FIND_DATAW findData;        IntPtr findHandle = INVALID_HANDLE_VALUE;        var info = new List<Info>();        try { findHandle = FindFirstFileW(directory + @"*", out findData); if (findHandle != INVALID_HANDLE_VALUE) {     do {         if (findData.cFileName == "." || findData.cFileName == "..") continue;         string fullpath = directory + (directory.EndsWith("\") ? "" : "\") + findData.cFileName;         bool isDir = false;         if ((findData.dwFileAttributes & FileAttributes.Directory) != 0) {  isDir = true;  info.AddRange(RecursiveScan2(fullpath));         }         info.Add(new Info()         {  CreatedDate = findData.ftCreationTime.ToDateTime(),  ModifiedDate = findData.ftLastWriteTime.ToDateTime(),  IsDirectory = isDir,  Path = fullpath         });     }     while (FindNextFile(findHandle, out findData)); }        } finally { if (findHandle != INVALID_HANDLE_VALUE) FindClose(findHandle);        }        return info;    }

扩展方法:

 public static class FILETIMEExtensions {        public static DateTime ToDateTime(this System.Runtime.InteropServices.ComTypes.FILETIME filetime ) { long highBits = filetime.dwHighDateTime; highBits = highBits << 32; return DateTime.FromFileTimeUtc(highBits + (long)filetime.dwLowDateTime);        }    }

互操作性定义为:

    [Dllimport("kernel32.dll", CharSet = CharSet.Unipre, SetLastError = true)]    public static extern IntPtr FindFirstFileW(string lpFileName, out WIN32_FIND_DATAW lpFindFileData);    [Dllimport("kernel32.dll", CharSet = CharSet.Unipre)]    public static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATAW lpFindFileData);    [Dllimport("kernel32.dll")]    public static extern bool FindClose(IntPtr hFindFile);    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unipre)]    public struct WIN32_FIND_DATAW {        public FileAttributes dwFileAttributes;        internal System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;        internal System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;        internal System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;        public int nFileSizeHigh;        public int nFileSizeLow;        public int dwReserved0;        public int dwReserved1;        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]        public string cFileName;        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]        public string cAlternateFileName;    }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/432975.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号