다음을 통해 공유


방법: 지정된 특성 또는 이름을 갖는 파일 쿼리

업데이트: 2007년 11월

이 예제에서는 지정된 디렉터리 트리에서 지정된 파일 이름 확장명(예: ".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 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;
    }
}

코드 컴파일

  • .NET Framework 버전 3.5를 대상으로 하는 Visual Studio 프로젝트를 만듭니다. 이 프로젝트에는 기본적으로 System.Linq 네임스페이스에 대한 using 지시문(C#) 또는 Imports 문(Visual Basic)과 System.Core.dll에 대한 참조가 있습니다. C# 프로젝트에서는 System.IO 네임스페이스에 대한 using 지시문을 추가합니다.

  • 프로젝트에 이 코드를 복사합니다.

  • F5 키를 눌러 프로그램을 컴파일하고 실행합니다.

  • 아무 키나 눌러 콘솔 창을 닫습니다.

강력한 프로그래밍

여러 형식의 문서와 파일의 콘텐츠에서 많이 수행되는 쿼리 작업의 경우 Windows Desktop Search 엔진을 사용해 보십시오.

참고 항목

개념

LINQ to Objects

LINQ 및 파일 디렉터리