如何:查询具有指定特性或名称的文件

此示例演示如何查找指定目录树中具有指定文件扩展名(例如“.txt”)的所有文件, 还演示如何根据创建时间返回树中最新或最旧的文件。

示例

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

编译代码

  • 创建一个以 .NET Framework 3.5 版为目标的 Visual Studio 项目。 默认情况下,该项目具有对 System.Core.dll 的引用以及针对 System.Linq 命名空间的 using 指令 (C#) 或 Imports 语句 (Visual Basic)。 在 C# 项目中,添加 System.IO 命名空间的 using 指令。

  • 将此代码复制到您的项目。

  • 按 F5 编译并运行程序。

  • 按任意键退出控制台窗口。

可靠编程

若要对多种类型的文档和文件的内容执行大量查询操作,请考虑使用 Windows Desktop Search(Windows 桌面搜索)引擎。

请参见

概念

LINQ to Objects

LINQ 和文件目录