次の方法で共有


方法: ディレクトリ ツリー内の最大のファイルを照会する (LINQ) (Visual Basic)

この例では、ファイル サイズに関連する 5 つのクエリをバイト単位で示します。

  • 最大ファイルのサイズ (バイト単位) を取得する方法。

  • 最小ファイルのサイズをバイト単位で取得する方法。

  • 指定したルート フォルダーの下にある 1 つ以上のフォルダーから、 FileInfo オブジェクトの最大または最小のファイルを取得する方法。

  • 最大 10 個のファイルなどのシーケンスを取得する方法。

  • 指定したサイズ未満のファイルを無視して、ファイル サイズ (バイト単位) に基づいてファイルをグループに並べ替える方法。

次の例には、ファイル サイズに応じてファイルのクエリとグループ化を行う方法を示す 5 つのクエリが含まれています (バイト単位)。 これらの例を簡単に変更して、 FileInfo オブジェクトの他のプロパティに基づいてクエリを実行できます。

Module QueryBySize  
    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)  
  
        ' Return the size of the largest file  
        Dim maxSize = Aggregate aFile In fileList Into Max(GetFileLength(aFile))  
  
        'Dim maxSize = fileLengths.Max  
        Console.WriteLine("The length of the largest file under {0} is {1}", _  
                          root, maxSize)  
  
        ' Return the FileInfo object of the largest file  
        ' by sorting and selecting from the beginning of the list  
        Dim filesByLengDesc = From file In fileList _  
                              Let filelength = GetFileLength(file) _  
                              Where filelength > 0 _  
                              Order By filelength Descending _  
                              Select file  
  
        Dim longestFile = filesByLengDesc.First  
  
        Console.WriteLine("The largest file under {0} is {1} with a length of {2} bytes", _  
                          root, longestFile.FullName, longestFile.Length)  
  
        Dim smallestFile = filesByLengDesc.Last  
  
        Console.WriteLine("The smallest file under {0} is {1} with a length of {2} bytes", _  
                                root, smallestFile.FullName, smallestFile.Length)  
  
        ' Return the FileInfos for the 10 largest files  
        ' Based on a previous query, but nothing is executed  
        ' until the For Each statement below.  
        Dim tenLargest = From file In filesByLengDesc Take 10  
  
        Console.WriteLine("The 10 largest files under {0} are:", root)  
  
        For Each fi As System.IO.FileInfo In tenLargest  
            Console.WriteLine("{0}: {1} bytes", fi.FullName, fi.Length)  
        Next  
  
        ' Group files according to their size,  
        ' leaving out the ones under 200K  
        Dim sizeGroups = From file As System.IO.FileInfo In fileList _  
                         Where file.Length > 0 _  
                         Let groupLength = file.Length / 100000 _  
                         Group file By groupLength Into fileGroup = Group _  
                         Where groupLength >= 2 _  
                         Order By groupLength Descending  
  
        For Each group In sizeGroups  
            Console.WriteLine(group.groupLength + "00000")  
  
            For Each item As System.IO.FileInfo In group.fileGroup  
                Console.WriteLine("   {0}: {1}", item.Name, item.Length)  
            Next  
        Next  
  
        ' Keep the console window open in debug mode  
        Console.WriteLine("Press any key to exit.")  
        Console.ReadKey()  
  
    End Sub  
  
    ' This method is used to catch the possible exception  
    ' that can be raised when accessing the FileInfo.Length property.  
    ' In this particular case, it is safe to ignore the exception.  
    Function GetFileLength(ByVal fi As System.IO.FileInfo) As Long  
        Dim retval As Long  
        Try  
            retval = fi.Length  
        Catch ex As FileNotFoundException  
            ' If a file is no longer present,  
            ' just return zero bytes.
            retval = 0  
        End Try  
  
        Return retval  
    End Function  
End Module  

1 つ以上の完全な FileInfo オブジェクトを返すには、まずクエリでデータ ソース内の各オブジェクトを調べ、Length プロパティの値で並べ替える必要があります。 その後、最も長い単独のものか一連のシーケンスを返すことができます。 Firstを使用して、リスト内の最初の要素を返します。 Takeを使用して、最初の n 個の要素を返します。 リストの先頭に最小の要素を配置する降順の並べ替え順序を指定します。

クエリは、FileInfoの呼び出しでGetFiles オブジェクトが作成されてからの期間中に別のスレッドでファイルが削除された場合に発生する可能性のある例外を使用するために、別のメソッドを呼び出してファイル サイズをバイト単位で取得します。 FileInfo オブジェクトが既に作成されている場合でも、FileInfo オブジェクトがプロパティに初めてアクセスしたときに最新のサイズ (バイト単位) を使用してLength プロパティを更新しようとするため、例外が発生する可能性があります。 この操作をクエリの外側の try-catch ブロックに配置することで、副作用を引き起こす可能性のあるクエリでの操作を回避するというルールに従います。 一般に、アプリケーションが不明な状態に残らないように、例外を使用するときは細心の注意を払う必要があります。

コードをコンパイルする

System.Linq 名前空間の Imports ステートメントを使用して、Visual Basic コンソール アプリケーション プロジェクトを作成します。

こちらも参照ください