Procedura: Enumerare directory e fileHow to: Enumerate directories and files

Le raccolte enumerabili offrono prestazioni migliori rispetto alle matrici quando si lavora con grandi raccolte di file e directory.Enumerable collections provide better performance than arrays when you work with large collections of directories and files. Per enumerare directory e file, usare metodi che restituiscono una raccolta enumerabile di nomi di directory o file o dei rispettivi oggetti DirectoryInfo, FileInfo o FileSystemInfo.To enumerate directories and files, use methods that return an enumerable collection of directory or file names, or their DirectoryInfo, FileInfo, or FileSystemInfo objects.

Se si vogliono cercare e restituire solo i nomi di directory o file, usare i metodi di enumerazione della classe Directory.If you want to search and return only the names of directories or files, use the enumeration methods of the Directory class. Se si vogliono cercare e restituire altre proprietà di directory o file, usare le classi DirectoryInfo e FileSystemInfo.If you want to search and return other properties of directories or files, use the DirectoryInfo and FileSystemInfo classes.

È possibile usare raccolte enumerabili ottenute da questi metodi come parametro IEnumerable<T> per i costruttori di classi di raccolte, come List<T>.You can use enumerable collections from these methods as the IEnumerable<T> parameter for constructors of collection classes like List<T>.

La tabella seguente riepiloga i metodi che restituiscono raccolte enumerabili di file e directory:The following table summarizes the methods that return enumerable collections of files and directories:

Per cercare e restituireTo search and return Usare il metodoUse method
Nomi di directoryDirectory names Directory.EnumerateDirectories
Informazioni sulle directory (DirectoryInfo)Directory information (DirectoryInfo) DirectoryInfo.EnumerateDirectories
Nomi fileFile names Directory.EnumerateFiles
Informazioni sui file (FileInfo)File information (FileInfo) DirectoryInfo.EnumerateFiles
Nomi di voci del file systemFile system entry names Directory.EnumerateFileSystemEntries
Informazioni sulle voci di file system (FileSystemInfo)File system entry information (FileSystemInfo) DirectoryInfo.EnumerateFileSystemInfos
Nomi di file e directoryDirectory and file names Directory.EnumerateFileSystemEntries

Nota

Anche se è possibile enumerare immediatamente tutti i file presenti nelle sottodirectory della directory padre usando l'opzione AllDirectories dell'enumerazione SearchOption facoltativa, errori UnauthorizedAccessException possono rendere incompleta l'enumerazione.Although you can immediately enumerate all the files in the subdirectories of a parent directory by using the AllDirectories option of the optional SearchOption enumeration, UnauthorizedAccessException errors may make the enumeration incomplete. È possibile intercettare queste eccezioni enumerando prima di tutto le directory e quindi i file.You can catch these exceptions by first enumerating directories and then enumerating files.

Esempi: Usare la classe DirectoryExamples: Use the Directory class

L'esempio seguente usa il metodo Directory.EnumerateDirectories(String) per ottenere un elenco dei nomi delle directory di primo livello in un percorso specificato.The following example uses the Directory.EnumerateDirectories(String) method to get a list of the top-level directory names in a specified path.

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

class Program
{
    private static void Main(string[] args)
    {
        try
        {
            // Set a variable to the My Documents path.
            string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            List<string> dirs = new List<string>(Directory.EnumerateDirectories(docPath));
                    
            foreach (var dir in dirs)
            {
                Console.WriteLine($"{dir.Substring(dir.LastIndexOf(Path.DirectorySeparatorChar) + 1)}");
            }
            Console.WriteLine($"{dirs.Count} directories found.");
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine(ex.Message);
        }
        catch (PathTooLongException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
Imports System.Collections.Generic
Imports System.IO

Module Module1

    Sub Main()
        Try
            Dim dirPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

            Dim dirs As List(Of String) = New List(Of String)(Directory.EnumerateDirectories(dirPath))

            For Each folder In dirs
                Console.WriteLine($"{dir.Substring(dir.LastIndexOf(Path.DirectorySeparatorChar) + 1)}")
            Next
            Console.WriteLine($"{dirs.Count} directories found.")
        Catch ex As UnauthorizedAccessException
            Console.WriteLine(ex.Message)
        Catch ex As PathTooLongException
            Console.WriteLine(ex.Message)
        End Try

    End Sub
End Module

L'esempio seguente usa il metodo Directory.EnumerateFiles(String, String, SearchOption) per enumerare in modo ricorsivo tutti i nomi file in una directory e nelle relative sottodirectory che soddisfano un criterio specifico.The following example uses the Directory.EnumerateFiles(String, String, SearchOption) method to recursively enumerate all file names in a directory and subdirectories that match a certain pattern. L'esempio legge quindi ogni riga di ogni file e visualizza le righe che contengono una stringa specificata, con i nomi file e i percorsi corrispondenti.It then reads each line of each file and displays the lines that contain a specified string, with their filenames and paths.

using System;
using System.IO;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            // Set a variable to the My Documents path.
            string docPath =
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var files = from file in Directory.EnumerateFiles(docPath, "*.txt", SearchOption.AllDirectories)
                        from line in File.ReadLines(file)
                        where line.Contains("Microsoft")
                        select new
                        {
                            File = file,
                            Line = line
                        };

            foreach (var f in files)
            {
                Console.WriteLine($"{f.File}\t{f.Line}");
            }
            Console.WriteLine($"{files.Count().ToString()} files found.");
        }
        catch (UnauthorizedAccessException uAEx)
        {
            Console.WriteLine(uAEx.Message);
        }
        catch (PathTooLongException pathEx)
        {
            Console.WriteLine(pathEx.Message);
        }
    }
}
Imports System.IO
Imports System.Xml.Linq

Module Module1

    Sub Main()
        Try
            Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            Dim files = From chkFile In Directory.EnumerateFiles(docPath, "*.txt", SearchOption.AllDirectories)
                        From line In File.ReadLines(chkFile)
                        Where line.Contains("Microsoft")
                        Select New With {.curFile = chkFile, .curLine = line}

            For Each f In files
                Console.WriteLine($"{f.File}\t{f.Line}")
            Next
            Console.WriteLine($"{files.Count} files found.")
        Catch uAEx As UnauthorizedAccessException
            Console.WriteLine(uAEx.Message)
        Catch pathEx As PathTooLongException
            Console.WriteLine(pathEx.Message)
        End Try
    End Sub
End Module

Esempi: Usare la classe DirectoryInfoExamples: Use the DirectoryInfo class

L'esempio seguente usa il metodo DirectoryInfo.EnumerateDirectories per elencare una raccolta di directory di primo livello la cui proprietà CreationTimeUtc è precedente a un valore DateTime specifico.The following example uses the DirectoryInfo.EnumerateDirectories method to list a collection of top-level directories whose CreationTimeUtc is earlier than a certain DateTime value.

using System;
using System.IO;

namespace EnumDir
{
    class Program
    {
        static void Main(string[] args)
        {
            // Set a variable to the Documents path.
            string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            DirectoryInfo dirPrograms = new DirectoryInfo(docPath);
            DateTime StartOf2009 = new DateTime(2009, 01, 01);

            var dirs = from dir in dirPrograms.EnumerateDirectories()
            where dir.CreationTimeUtc > StartOf2009
            select new
            {
                ProgDir = dir,
            };

            foreach (var di in dirs)
            {
                Console.WriteLine($"{di.ProgDir.Name}");
            }

        }
    }
}
// </Snippet1>
Imports System.IO

Module Module1

    Sub Main()

        Dim dirPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        Dim dirPrograms As New DirectoryInfo(dirPath)
        Dim StartOf2009 As New DateTime(2009, 1, 1)

        Dim dirs = From dir In dirPrograms.EnumerateDirectories()
                   Where dir.CreationTimeUtc > StartOf2009

        For Each di As DirectoryInfo In dirs
            Console.WriteLine("{0}", di.Name)
        Next

    End Sub

End Module

L'esempio seguente usa il metodo DirectoryInfo.EnumerateFiles per elencare tutti i file la cui proprietà Length supera i 10 MB.The following example uses the DirectoryInfo.EnumerateFiles method to list all files whose Length exceeds 10MB. Questo esempio enumera prima di tutto le directory di primo livello per intercettare possibili eccezioni di accesso non autorizzato e quindi enumera i file.This example first enumerates the top-level directories, to catch possible unauthorized access exceptions, and then enumerates the files.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // Set a variable to the My Documents path.
        string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        DirectoryInfo diTop = new DirectoryInfo(docPath);

        try
        {
            foreach (var fi in diTop.EnumerateFiles())
            {
                try
                {
                    // Display each file over 10 MB;
                    if (fi.Length > 10000000)
                    {
                        Console.WriteLine($"{fi.FullName}\t\t{fi.Length.ToString("NO")}");
                    }
                }
                catch (UnauthorizedAccessException unAuthTop)
                {
                    Console.WriteLine($"{unAuthTop.Message}");
                }
            }
            
            foreach (var di in diTop.EnumerateDirectories("*"))
            {
                try
                {
                    foreach (var fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
                    {
                        try
                        {
                            // Display each file over 10 MB;
                            if (fi.Length > 10000000)
                            {
                                Console.WriteLine($"{fi.FullName}\t\t{fi.Length.ToString("NO")}");
                            }
                        }
                        catch (UnauthorizedAccessException unAuthFile)
                        {
                            Console.WriteLine($"unAuthFile: {unAuthFile.Message}");
                        }
                    }
                }
                catch (UnauthorizedAccessException unAuthSubDir)
                {
                    Console.WriteLine($"unAuthSubDir: {unAuthSubDir.Message}");
                }
            }
        }
        catch (DirectoryNotFoundException dirNotFound)
        {
            Console.WriteLine($"{dirNotFound.Message}");
        }
        catch (UnauthorizedAccessException unAuthDir)
        {
            Console.WriteLine($"unAuthDir: {unAuthDir.Message}");
        }
        catch (PathTooLongException longPath)
        {
            Console.WriteLine($"{longPath.Message}");
        }
    }
}
Imports System.IO

Class Program
    Public Shared Sub Main(ByVal args As String())
        Dim dirPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        Dim diTop As New DirectoryInfo(dirPath)
        Try
            For Each fi In diTop.EnumerateFiles()
                Try
                    ' Display each file over 10 MB;
                    If fi.Length > 10000000 Then
                        Console.WriteLine("{0}" & vbTab & vbTab & "{1}", fi.FullName, fi.Length.ToString("N0"))
                    End If
                Catch unAuthTop As UnauthorizedAccessException
                    Console.WriteLine($"{unAuthTop.Message}")
                End Try
            Next

            For Each di In diTop.EnumerateDirectories("*")
                Try
                    For Each fi In di.EnumerateFiles("*", SearchOption.AllDirectories)
                        Try
                            ' // Display each file over 10 MB;
                            If fi.Length > 10000000 Then
                                Console.WriteLine("{0}" & vbTab &
                                vbTab & "{1}", fi.FullName, fi.Length.ToString("N0"))
                            End If
                        Catch unAuthFile As UnauthorizedAccessException
                            Console.WriteLine($"unAuthFile: {unAuthFile.Message}")
                        End Try
                    Next
                Catch unAuthSubDir As UnauthorizedAccessException
                    Console.WriteLine($"unAuthSubDir: {unAuthSubDir.Message}")
                End Try
            Next
        Catch dirNotFound As DirectoryNotFoundException
            Console.WriteLine($"{dirNotFound.Message}")
        Catch unAuthDir As UnauthorizedAccessException
            Console.WriteLine($"unAuthDir: {unAuthDir.Message}")
        Catch longPath As PathTooLongException
            Console.WriteLine($"{longPath.Message}")
        End Try
    End Sub
End Class

Vedere ancheSee also