How to recursively list all the files in a directory in C#?

前端 未结 22 2529
长发绾君心
长发绾君心 2020-11-22 00:07

How to recursively list all the files in a directory and child directories in C#?

相关标签:
22条回答
  • 2020-11-22 00:38

    To avoid the UnauthorizedAccessException, I use:

    var files = GetFiles(@"C:\", "*.*", SearchOption.AllDirectories);
    foreach (var file in files)
    {
        Console.WriteLine($"{file}");
    }
    
    public static IEnumerable<string> GetFiles(string path, string searchPattern, SearchOption searchOption)
    {
        var foldersToProcess = new List<string>()
        {
            path
        };
    
        while (foldersToProcess.Count > 0)
        {
            string folder = foldersToProcess[0];
            foldersToProcess.RemoveAt(0);
    
            if (searchOption.HasFlag(SearchOption.AllDirectories))
            {
                //get subfolders
                try
                {
                    var subfolders = Directory.GetDirectories(folder);
                    foldersToProcess.AddRange(subfolders);
                }
                catch (Exception ex)
                {
                    //log if you're interested
                }
            }
    
            //get files
            var files = new List<string>();
            try
            {
                files = Directory.GetFiles(folder, searchPattern, SearchOption.TopDirectoryOnly).ToList();
            }
            catch (Exception ex)
            {
                //log if you're interested
            }
    
            foreach (var file in files)
            {
                yield return file;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:39

    Short and simple solution

    string dir = @"D:\PATH";
    
    DateTime from_date = DateTime.Now.Date;
    DateTime to_date = DateTime.Now.Date.AddHours(23);
    var files = Directory.EnumerateFiles(dir, "*.*",SearchOption.AllDirectories).Select(i=>new FileInfo(i))
    .Where(file=>file.LastWriteTime >= from_date && file.LastWriteTime <= to_date);
    foreach(var fl in files)
        Console.WriteLine(fl.FullName);
    
    0 讨论(0)
  • 2020-11-22 00:42

    A simple and clean solution

    /// <summary>
    /// Scans a folder and all of its subfolders recursively, and updates the List of files
    /// </summary>
    /// <param name="sFullPath">Full path of the folder</param>
    /// <param name="files">The list, where the output is expected</param>
    internal static void EnumerateFiles(string sFullPath, List<FileInfo> fileInfoList)
    {
        try
        {
            DirectoryInfo di = new DirectoryInfo(sFullPath);
            FileInfo[] files = di.GetFiles();
    
            foreach (FileInfo file in files)
                fileInfoList.Add(file);
    
            //Scan recursively
            DirectoryInfo[] dirs = di.GetDirectories();
            if (dirs == null || dirs.Length < 1)
                return;
            foreach (DirectoryInfo dir in dirs)
                EnumerateFiles(dir.FullName, fileInfoList);
    
        }
        catch (Exception ex)
        {
            Logger.Write("Exception in Helper.EnumerateFiles", ex);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:45

    Note that in .NET 4.0 there are (supposedly) iterator-based (rather than array-based) file functions built in:

    foreach (string file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
    {
        Console.WriteLine(file);
    }
    

    At the moment I'd use something like below; the inbuilt recursive method breaks too easily if you don't have access to a single sub-dir...; the Queue<string> usage avoids too much call-stack recursion, and the iterator block avoids us having a huge array.

    static void Main() {
        foreach (string file in GetFiles(SOME_PATH)) {
            Console.WriteLine(file);
        }
    }
    
    static IEnumerable<string> GetFiles(string path) {
        Queue<string> queue = new Queue<string>();
        queue.Enqueue(path);
        while (queue.Count > 0) {
            path = queue.Dequeue();
            try {
                foreach (string subDir in Directory.GetDirectories(path)) {
                    queue.Enqueue(subDir);
                }
            }
            catch(Exception ex) {
                Console.Error.WriteLine(ex);
            }
            string[] files = null;
            try {
                files = Directory.GetFiles(path);
            }
            catch (Exception ex) {
                Console.Error.WriteLine(ex);
            }
            if (files != null) {
                for(int i = 0 ; i < files.Length ; i++) {
                    yield return files[i];
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:46

    Listing files and folders to model, custom implementation.
    This creates a full listing of all files and folders starting from your start directory.

    public class DirOrFileModel
        {
            #region Private Members
    
            private string _name;
            private string _location;
            private EntryType _entryType;
    
            #endregion
    
            #region Bindings
    
            public string Name
            {
                get { return _name; }
                set
                {
                    if (value == _name) return;
                    _name = value;
                }
            }
    
            public string Location
            {
                get { return _location; }
                set
                {
                    if (value == _location) return;
                    _location = value;
                }
            }
    
            public EntryType EntryType
            {
                get { return _entryType; }
                set
                {
                    if (value == _entryType) return;
                    _entryType = value;
                }
            }
    
            public ObservableCollection<DirOrFileModel> Entries { get; set; }
    
            #endregion
    
            #region Constructor
    
            public DirOrFileModel()
            {
                Entries = new ObservableCollection<DirOrFileModel>();
            }
    
            #endregion
        }
    
        public enum EntryType
        {
            Directory = 0,
            File = 1
        }
    

    Method:

     static DirOrFileModel DirSearch(DirOrFileModel startDir)
            {
                var currentDir = startDir;
                try
                {
                    foreach (string d in Directory.GetDirectories(currentDir.Location))
                    {
                        var newDir = new DirOrFileModel
                        {
                            EntryType = EntryType.Directory,
                            Location = d,
                            Name = Path.GetFileName(d)
                        };
                        currentDir.Entries.Add(newDir);
    
                        DirSearch(newDir);
                    }
    
                    foreach (string f in Directory.GetFiles(currentDir.Location))
                    {
                        var newFile = new DirOrFileModel
                        {
                            EntryType = EntryType.File,
                            Location = f,
                            Name = Path.GetFileNameWithoutExtension(f)
                        };
                        currentDir.Entries.Add(newFile);
                    }
    
                }
                catch (Exception excpt)
                {
                    Console.WriteLine(excpt.Message);
                }
                return startDir;
            }
    

    Usage:

    var dir = new DirOrFileModel
                {
                    Name = "C",
                    Location = @"C:\",
                    EntryType = EntryType.Directory
                };
    
                dir = DirSearch(dir);
    
    0 讨论(0)
  • 2020-11-22 00:47
    private void GetFiles(DirectoryInfo dir, ref List<FileInfo> files)
    {
        try
        {
            files.AddRange(dir.GetFiles());
            DirectoryInfo[] dirs = dir.GetDirectories();
            foreach (var d in dirs)
            {
                GetFiles(d, ref files);
            }
        }
        catch (Exception e)
        {
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题