C# 列出目录+子目录中的所有文件和目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12332451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:54:47  来源:igfitidea点击:

List all files and directories in a directory + subdirectories

c#directorysubdirectorygetdirectories

提问by derp_in_mouth

I want to list every file and directory contained in a directory and subdirectories of that directory. If I chose C:\ as the directory, the program would get every name of every file and folder on the hard drive that it had access to.

我想列出目录及其子目录中包含的每个文件和目录。如果我选择 C:\ 作为目录,程序将获取硬盘驱动器上它有权访问的每个文件和文件夹的每个名称。

A list might look like

列表可能看起来像

fd.txt
fd.txt
fd\a\
fd\b\
fd\a.txt
fd\a.txt
fd\a\a\
fd\a\b\
fd\b.txt
fd\b.txt
fd\b\a
fd\b\b
fd\a\a.txt
fd\a\a\a\
fd\a\b.txt
fd\a\b\a
fd\b\a.txt
fd\b\a\a\
fd\b\b.txt
fd\b\b\a

回答by Guffa

Use the GetDirectoriesand GetFilesmethods to get the folders and files.

使用GetDirectoriesGetFiles方法获取文件夹和文件。

Use the SearchOptionAllDirectoriesto get the folders and files in the subfolders also.

还可以使用获取子文件夹中的文件夹和文件。SearchOptionAllDirectories

回答by Ruslan F.

string[] allfiles = Directory.GetFiles("path/to/dir", "*.*", SearchOption.AllDirectories);

where *.*is pattern to match files

*.*匹配文件的模式在哪里

If the Directory is also needed you can go like this:

如果还需要目录,您可以这样做:

 foreach (var file in allfiles){
     FileInfo info = new FileInfo(file);
 // Do something with the Folder or just add them to a list via nameoflist.add();
 }

回答by Krishna Sarma

I am afraid, the GetFilesmethod returns list of files but not the directories. The list in the question prompts me that the result should include the folders as well. If you want more customized list, you may try calling GetFilesand GetDirectoriesrecursively. Try this:

恐怕,该GetFiles方法返回文件列表而不是目录。问题中的列表提示我结果也应包括文件夹。如果您想要更多自定义列表,您可以尝试调用GetFilesGetDirectories递归。尝试这个:

List<string> AllFiles = new List<string>();
void ParsePath(string path)
{
    string[] SubDirs = Directory.GetDirectories(path);
    AllFiles.AddRange(SubDirs);
    AllFiles.AddRange(Directory.GetFiles(path));
    foreach (string subdir in SubDirs)
        ParsePath(subdir);
}

Tip: You can use FileInfoand DirectoryInfoclasses if you need to check any specific attribute.

提示:如果您需要检查任何特定属性,您可以使用FileInfoDirectoryInfo类。

回答by Alastair Maw

Directory.GetFileSystemEntriesexists in .NET 4.0+ and returns both files and directories. Call it like so:

Directory.GetFileSystemEntries存在于 .NET 4.0+ 中并返回文件和目录。像这样称呼它:

string[] entries = Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories);

Note that it won't cope with attempts to list the contents of subdirectories that you don't have access to (UnauthorizedAccessException), but it may be sufficient for your needs.

请注意,它不会处理列出您无权访问的子目录内容的尝试 (UnauthorizedAccessException),但它可能足以满足您的需要。

回答by aah

using System.IO;
using System.Text;
string[] filePaths = Directory.GetFiles(@"path", "*.*", SearchOption.AllDirectories);

回答by Evan Dangol

public static void DirectorySearch(string dir)
{
    try
    {
        foreach (string f in Directory.GetFiles(dir))
        {
            Console.WriteLine(Path.GetFileName(f));
        }
        foreach (string d in Directory.GetDirectories(dir))
        {
            Console.WriteLine(Path.GetFileName(d));
            DirectorySearch(d);
        }
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

回答by Shubham

If you don't have access to a subfolder inside the directory tree, Directory.GetFiles stops and throws the exception resulting in a null value in the receiving string[].

如果您无权访问目录树中的子文件夹,Directory.GetFiles 将停止并引发异常,从而导致接收字符串 [] 中的值为空。

Here, see this answer https://stackoverflow.com/a/38959208/6310707

在这里,看到这个答案 https://stackoverflow.com/a/38959208/6310707

It manages the exception inside the loop and keep on working untill the entire folder is traversed.

它管理循环内的异常并继续工作,直到遍历整个文件夹。

回答by Markus

The following example the fastest(not parallelized) way list files and sub-folders in a directory tree handling exceptions. It would be faster to use Directory.EnumerateDirectories using SearchOption.AllDirectories to enumerate all directories, but this method will fail if hits a UnauthorizedAccessException or PathTooLongException.

下面的示例以最快(非并行化)方式列出目录树中的文件和子文件夹处理异常。使用 Directory.EnumerateDirectories 使用 SearchOption.AllDirectories 枚举所有目录会更快,但如果遇到 UnauthorizedAccessException 或 PathTooLongException,此方法将失败。

Uses the generic Stack collection type, which is a last in first out (LIFO) stack and does not use recursion. From https://msdn.microsoft.com/en-us/library/bb513869.aspx, allows you to enumerate all sub-directories and files and deal effectively with those exceptions.

使用通用 Stack 集合类型,它是后进先出 (LIFO) 堆栈并且不使用递归。来自https://msdn.microsoft.com/en-us/library/bb513869.aspx,允许您枚举所有子目录和文件并有效处理这些异常。

    public class StackBasedIteration
{
    static void Main(string[] args)
    {
        // Specify the starting folder on the command line, or in 
        // Visual Studio in the Project > Properties > Debug pane.
        TraverseTree(args[0]);

        Console.WriteLine("Press any key");
        Console.ReadKey();
    }

    public static void TraverseTree(string root)
    {
        // Data structure to hold names of subfolders to be
        // examined for files.
        Stack<string> dirs = new Stack<string>(20);

        if (!System.IO.Directory.Exists(root))
        {
            throw new ArgumentException();
        }
        dirs.Push(root);

        while (dirs.Count > 0)
        {
            string currentDir = dirs.Pop();
            string[] subDirs;
            try
            {
                subDirs = System.IO.Directory.EnumerateDirectories(currentDir); //TopDirectoryOnly
            }
            // An UnauthorizedAccessException exception will be thrown if we do not have
            // discovery permission on a folder or file. It may or may not be acceptable 
            // to ignore the exception and continue enumerating the remaining files and 
            // folders. It is also possible (but unlikely) that a DirectoryNotFound exception 
            // will be raised. This will happen if currentDir has been deleted by
            // another application or thread after our call to Directory.Exists. The 
            // choice of which exceptions to catch depends entirely on the specific task 
            // you are intending to perform and also on how much you know with certainty 
            // about the systems on which this code will run.
            catch (UnauthorizedAccessException e)
            {                    
                Console.WriteLine(e.Message);
                continue;
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
                continue;
            }

            string[] files = null;
            try
            {
                files = System.IO.Directory.EnumerateFiles(currentDir);
            }

            catch (UnauthorizedAccessException e)
            {

                Console.WriteLine(e.Message);
                continue;
            }

            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
                continue;
            }
            // Perform the required action on each file here.
            // Modify this block to perform your required task.
            foreach (string file in files)
            {
                try
                {
                    // Perform whatever action is required in your scenario.
                    System.IO.FileInfo fi = new System.IO.FileInfo(file);
                    Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
                }
                catch (System.IO.FileNotFoundException e)
                {
                    // If file was deleted by a separate application
                    //  or thread since the call to TraverseTree()
                    // then just continue.
                    Console.WriteLine(e.Message);
                    continue;
                }
                catch (UnauthorizedAccessException e)
                {                    
                    Console.WriteLine(e.Message);
                    continue;
                }
            }

            // Push the subdirectories onto the stack for traversal.
            // This could also be done before handing the files.
            foreach (string str in subDirs)
                dirs.Push(str);
        }
    }
}

回答by Sascha

the logical and ordered way:

逻辑和有序的方式:

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace DirLister
{
class Program
{
    public static void Main(string[] args)
    {
        //with reflection I get the directory from where this program is running, thus listing all files from there and all subdirectories
        string[] st = FindFileDir(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
        using ( StreamWriter sw = new StreamWriter("listing.txt", false ) )
        {
            foreach(string s in st)
            {
                //I write what I found in a text file
                sw.WriteLine(s);
            }
        }
    }

    private static string[] FindFileDir(string beginpath)
    {
        List<string> findlist = new List<string>();

        /* I begin a recursion, following the order:
         * - Insert all the files in the current directory with the recursion
         * - Insert all subdirectories in the list and rebegin the recursion from there until the end
         */
        RecurseFind( beginpath, findlist );

        return findlist.ToArray();
    }

    private static void RecurseFind( string path, List<string> list )
    {
        string[] fl = Directory.GetFiles(path);
        string[] dl = Directory.GetDirectories(path);
        if ( fl.Length>0 || dl.Length>0 )
        {
            //I begin with the files, and store all of them in the list
            foreach(string s in fl)
                list.Add(s);
            //I then add the directory and recurse that directory, the process will repeat until there are no more files and directories to recurse
            foreach(string s in dl)
            {
                list.Add(s);
                RecurseFind(s, list);
            }
        }
    }
}
}

回答by Garry

I use the following code with a form that has 2 buttons, one for exit and the other to start. A folder browser dialog and a save file dialog. Code is listed below and works on my system Windows10 (64):

我将以下代码与具有 2 个按钮的表单一起使用,一个用于退出,另一个用于启动。文件夹浏览器对话框和保存文件对话框。下面列出了代码,适用于我的系统 Windows10 (64):

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Directory_List
{

    public partial class Form1 : Form
    {
        public string MyPath = "";
        public string MyFileName = "";
        public string str = "";

        public Form1()
        {
            InitializeComponent();
        }    
        private void cmdQuit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }    
        private void cmdGetDirectory_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            MyPath = folderBrowserDialog1.SelectedPath;    
            saveFileDialog1.ShowDialog();
            MyFileName = saveFileDialog1.FileName;    
            str = "Folder = " + MyPath + "\r\n\r\n\r\n";    
            DirectorySearch(MyPath);    
            var result = MessageBox.Show("Directory saved to Disk!", "", MessageBoxButtons.OK);
                Application.Exit();    
        }    
        public void DirectorySearch(string dir)
        {
                try
            {
                foreach (string f in Directory.GetFiles(dir))
                {
                    str = str + dir + "\" + (Path.GetFileName(f)) + "\r\n";
                }    
                foreach (string d in Directory.GetDirectories(dir, "*"))
                {

                    DirectorySearch(d);
                }
                        System.IO.File.WriteAllText(MyFileName, str);

            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}