Share via


Como: consulta de arquivos com um nome ou o atributo especificado

Este exemplo mostra como localizar todos os arquivos que têm uma extensão de nome de arquivo especificado (por exemplo ". txt") em uma árvore de diretório especificado.Ele também mostra como retornar tanto o arquivo mais recente ou mais antigo na árvore com base na hora de criação.

Exemplo

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 dir As New System.IO.DirectoryInfo(root)

        Dim fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories)

        ' 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
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.
        System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);

        // This method assumes that the application has discovery permissions
        // for all folders under the specified path.
        IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

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

Compilando o código

  • Criar um Visual Studio o projeto que se destina a .NET Framework versão 3.5.Por padrão, o projeto tem uma referência a System.Core.dll e um using diretiva (C#) ou Imports instrução (Visual Basic) para o namespace System. LINQ.No C# projetos, adicione um using diretriz para o namespace System. IO.

  • Copie este código para seu projeto.

  • Pressione F5 para compilar e executar o programa.

  • Pressione qualquer tecla para sair da janela do console.

Programação robusta

Para operações de consulta intensivo sobre o conteúdo de vários tipos de documentos e arquivos, considere o uso de O Windows Desktop Search engine.

Consulte também

Conceitos

LINQ to Objects

LINQ e diretórios de arquivos