Share via


Cómo: Buscar archivos con un nombre o atributo especificados

Actualización: noviembre 2007

En este ejemplo se muestra cómo buscar todos los archivos que tienen una extensión especificada (por ejemplo, ".txt") en un árbol de directorios especificado. También se muestra cómo devolver el archivo más reciente o más antiguo del árbol según la hora de creación.

Ejemplo

Module FindFileByExtension

    Sub Main()

        ' Change the drive\path if necessary
        Dim root As String = "C:\Program Files\Microsoft Visual Studio 9.0"

        'Take a snapshot of the folder contents
        Dim fileList = GetFiles(root)

        ' This query will produce the full path for all .txt files
        ' under the specified folder including subfolders.
        ' It orders the list according to the file name.
        Dim fileQuery = From file In fileList _
                        Where file.Extension = ".txt" _
                        Order By file.Name _
                        Select file

        For Each file In fileQuery
            Console.WriteLine(file.FullName)
        Next

        ' Create and execute a new query by using
        ' the previous query as a starting point.
        ' fileQuery is not executed again until the
        ' call to Last
        Dim fileQuery2 = From file In fileQuery _
                         Order By file.CreationTime _
                         Select file.Name, file.CreationTime

        ' Execute the query
        Dim newestFile = fileQuery2.Last

        Console.WriteLine("\r\nThe newest .txt file is {0}. Creation time: {1}", _
                newestFile.Name, newestFile.CreationTime)

        ' Keep the console window open in debug mode
        Console.WriteLine("Press any key to exit.")
        Console.ReadKey()

    End Sub

    ' Function to retrieve a list of files. Note that this is a copy
    ' of the file information.
    Function GetFiles(ByVal root As String) As System.Collections.Generic.IEnumerable(Of System.IO.FileInfo)
        Return From file In My.Computer.FileSystem.GetFiles _
                  (root, FileIO.SearchOption.SearchAllSubDirectories, "*.*") _
               Select New System.IO.FileInfo(file)
    End Function
End Module
class FindFileByExtension
{
    // This query will produce the full path for all .txt files
    // under the specified folder including subfolders.
    // It orders the list according to the file name.
    static void Main()
    {
        string startFolder = @"c:\program files\Microsoft Visual Studio 9.0\";

        // Take a snapshot of the file system.
        IEnumerable<System.IO.FileInfo> fileList = GetFiles(startFolder);

        //Create the query
        IEnumerable<System.IO.FileInfo> fileQuery =
            from file in fileList
            where file.Extension == ".txt"
            orderby file.Name
            select file;

        //Execute the query. This might write out a lot of files!
        foreach (System.IO.FileInfo fi in fileQuery)
        {
            Console.WriteLine(fi.FullName);
        }

        // Create and execute a new query by using the previous 
        // query as a starting point. fileQuery is not 
        // executed again until the call to Last()
        var newestFile = 
            (from file in fileQuery
            orderby file.CreationTime
            select new { file.FullName, file.CreationTime })
            .Last();

        Console.WriteLine("\r\nThe newest .txt file is {0}. Creation time: {1}",
            newestFile.FullName, newestFile.CreationTime);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

    // This method assumes that the application has discovery 
    // permissions for all folders under the specified path.
    static IEnumerable<System.IO.FileInfo> GetFiles(string path)
    {
        if (!System.IO.Directory.Exists(path))
            throw new System.IO.DirectoryNotFoundException();

        string[] fileNames = null;
        List<System.IO.FileInfo> files = new List<System.IO.FileInfo>();

        fileNames = System.IO.Directory.GetFiles(path, "*.*", System.IO.SearchOption.AllDirectories);            
        foreach (string name in fileNames)
        {
            files.Add(new System.IO.FileInfo(name));
        }
        return files;
    }
}

Compilar el código

  • Cree un proyecto de Visual Studio destinado a la versión 3.5 de .NET Framework. De manera predeterminada, el proyecto incluye una referencia a System.Core.dll y una directiva using (C#) o una instrucción Imports (Visual Basic) para el espacio de nombres System.Linq. En los proyectos de C#, agregue una directiva using para el espacio de nombres System.IO.

  • Copie este código en el proyecto.

  • Presione F5 para compilar y ejecutar el programa.

  • Presione cualquier tecla para salir de la ventana de consola.

Programación eficaz

Cuando realice operaciones de consulta intensivas sobre el contenido de múltiples tipos de documentos y archivos, considere el uso del motor de Windows Desktop Search.

Vea también

Conceptos

LINQ to Objects

LINQ y directorios de archivos