Подтвердить что ты не робот

Список всех файлов и каталогов в каталоге + подкаталоги

Я хочу перечислить каждый файл и каталог, содержащиеся в каталоге и подкаталогах этого каталога. Если я выбрал C:\в качестве каталога, программа получит каждое имя каждого файла и папки на жестком диске, к которому у него был доступ.

Список может выглядеть как

fd\1.txt
fd\2.txt
fd\a\
fd\b\
fd\a\1.txt
fd\a\2.txt
fd\a\a\
fd\a\b\
fd\b\1.txt
fd\b\2.txt
fd\b\a
fd\b\b
fd\a\a\1.txt
fd\a\a\a\
fd\a\b\1.txt
fd\a\b\a
fd\b\a\1.txt
fd\b\a\a\
fd\b\b\1.txt
fd\b\b\a
4b9b3361

Ответ 1

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

где *.* - шаблон для соответствия файлам

Если каталог также необходим, вы можете сделать следующее:

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

Ответ 2

Directory.GetFileSystemEntries существует в .NET 4.0+ и возвращает оба файла и каталоги. Назовите его так:

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

Обратите внимание, что он не справится с попытками перечислить содержимое подкаталогов, к которым у вас нет доступа (UnauthorizedAccessException), но этого может быть достаточно для ваших нужд.

Ответ 3

Используйте GetDirectories и GetFiles методы для получения папок и файлов.

Используйте SearchOption AllDirectories, чтобы получить папки и файлы в подпапках.

Ответ 4

Я боюсь, метод GetFiles возвращает список файлов, но не каталоги. Список в вопросе подсказывает мне, что в результате должны быть указаны и папки. Если вы хотите больше настраиваемого списка, вы можете попробовать рекурсивно вызывать GetFiles и GetDirectories. Попробуйте следующее:

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

Совет. Вы можете использовать классы FileInfo и DirectoryInfo, если вам нужно проверить какой-либо конкретный атрибут.

Ответ 5

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

Ответ 6

Если у вас нет доступа к вложенной папке внутри дерева каталогов, Directory.GetFiles останавливается и выдает исключение, в результате чего получается нулевое значение в принимающей строке [].

Здесь, см. этот ответ fooobar.com/questions/90590/...

Он управляет исключением внутри цикла и продолжает работать до тех пор, пока не будет пройдена целая папка.

Ответ 7

В следующем примере самый быстрый (непараллельный) файл списка и подпапки в дереве обработки дерева каталогов. Было бы быстрее использовать Directory.EnumerateDirectories, используя SearchOption.AllDirectories, чтобы перечислять все каталоги, но этот метод не удастся, если удаляет UnauthorizedAccessException или PathTooLongException.

Использует общий тип коллекции 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);
        }
    }
}

Ответ 8

логический и упорядоченный способ:

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

Ответ 9

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