次の方法で共有


方法: フォルダーセット内の合計バイト数を照会する (LINQ) (Visual Basic)

この例では、指定したフォルダー内のすべてのファイルとそのすべてのサブフォルダーで使用される合計バイト数を取得する方法を示します。

Sum メソッドは、select 句で選択したすべての項目の値を追加します。 Minの代わりにMaxまたはSumメソッドを呼び出すことで、指定したディレクトリ ツリー内の最大または最小のファイルを取得するように、このクエリを簡単に変更できます。

Module QueryTotalBytes  
    Sub Main()  
  
        ' Change the drive\path if necessary.  
        Dim root As String = "C:\Program Files\Microsoft Visual Studio 9.0\VB"  
  
        'Take a snapshot of the folder contents.  
        ' This method assumes that the application has discovery permissions  
        ' for all folders under the specified path.  
        Dim fileList = My.Computer.FileSystem.GetFiles _  
                  (root, FileIO.SearchOption.SearchAllSubDirectories, "*.*")  
  
        Dim fileQuery = From file In fileList _  
                        Select GetFileLength(file)  
  
        ' Force execution and cache the results to avoid multiple trips to the file system.  
        Dim fileLengths = fileQuery.ToArray()  
  
        ' Find the largest file  
        Dim maxSize = Aggregate aFile In fileLengths Into Max()  
  
        ' Find the total number of bytes  
        Dim totalBytes = Aggregate aFile In fileLengths Into Sum()  
  
        Console.WriteLine("The largest file is " & maxSize & " bytes")  
        Console.WriteLine("There are " & totalBytes & " total bytes in " & _  
                          fileList.Count & " files under " & root)  
  
        ' 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.  
    Function GetFileLength(ByVal filename As String) As Long  
        Dim retval As Long  
        Try  
            Dim fi As New System.IO.FileInfo(filename)  
            retval = fi.Length  
        Catch ex As System.IO.FileNotFoundException  
            ' If a file is no longer present,  
            ' just return zero bytes.
            retval = 0  
        End Try  
  
        Return retval  
    End Function  
End Module  

指定したディレクトリ ツリー内のバイト数のみをカウントする必要がある場合は、LINQ クエリを作成せずに効率的にこれを行うことができます。これにより、リスト コレクションをデータ ソースとして作成するオーバーヘッドが発生します。 LINQ アプローチの有用性は、クエリが複雑になるにつれて、または同じデータ ソースに対して複数のクエリを実行する必要がある場合に増加します。

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

コードをコンパイルする

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

こちらも参照ください