Aracılığıyla paylaş


Nasıl yapılır: sorgu (LINQ) klasörler kümesi bayt toplam sayısı

Bu örnek, belirtilen bir klasördeki tüm dosyaları ve alt klasörleri tarafından kullanılan bayt sayısını almak gösterilmiştir.

Örnek

Sum Yöntemi, seçili tüm öğelerin değerini ekler select yan tümcesi.Çağıran belirtilen dizin ağacı içinde en büyük veya en küçük dosya almak için bu sorguyu kolayca değiştirebileceğiniz Min veya Max yöntemi yerine 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
class QuerySize
{
    public static void Main()
    {
        string startFolder = @"c:\program files\Microsoft Visual Studio 9.0\VC#";

        // Take a snapshot of the file system.
        // This method assumes that the application has discovery permissions
        // for all folders under the specified path.
        IEnumerable<string> fileList = System.IO.Directory.GetFiles(startFolder, "*.*", System.IO.SearchOption.AllDirectories);

        var fileQuery = from file in fileList
                        select GetFileLength(file);

        // Cache the results to avoid multiple trips to the file system.
        long[] fileLengths = fileQuery.ToArray();

        // Return the size of the largest file
        long largestFile = fileLengths.Max();

        // Return the total number of bytes in all the files under the specified folder.
        long totalBytes = fileLengths.Sum();

        Console.WriteLine("There are {0} bytes in {1} files under {2}",
            totalBytes, fileList.Count(), startFolder);
        Console.WriteLine("The largest files is {0} bytes.", largestFile);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    // This method is used to swallow the possible exception
    // that can be raised when accessing the System.IO.FileInfo.Length property.
    static long GetFileLength(string filename)
    {
        long retval;
        try
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(filename);
            retval = fi.Length;
        }
        catch (System.IO.FileNotFoundException)
        {
            // If a file is no longer present,
            // just add zero bytes to the total.
            retval = 0;
        }
        return retval;
    }
}

Yalnızca belirtilen dizin ağacında bayt sayısı varsa, bunu daha verimli bir şekilde oluşturmadan yapmak için bir LINQ sorgu veri kaynağı olarak liste koleksiyonu oluşturma yükü çeker.Kullanışlılığını LINQ yaklaşım, sorgu daha karmaşık hale geldikçe ya da çoklu sorgularda aynı veri kaynağına karşı çalıştırmak zorunda artırır.

Sorgu dosya uzunluğunu elde etmek için ayrı bir yöntemi çağırır.Sonra başka bir iş parçacığı üzerinde dosya silindiyse, yükseltilmiş olması olası durum kullanmak için bunu yapar FileInfo nesnenin oluşturulduğu çağrısında GetFiles.Olsa FileInfo nesne zaten oluşturuldu, özel durum ortaya çıkabilir çünkü bir FileInfo nesne çalýþýlýr yenilemek, Length özelliği ile en güncel uzunluk özelliği erişildiğinde ilk kez.Bu işlem sorgu dışında bir try-catch bloğu içinde yerleştirerek, yan etkilere neden olabilir sorguları işlemlerinde engelleme kuralı kod aşağıdadır.Genel olarak, bir uygulama bilinmeyen bir durumda sol değil emin olmak için özel durumlar tüketir, çok dikkatli olunmalıdır.

Kod Derleniyor

  • Oluşturma bir Visual Studio hedefleyen bir proje.net Framework sürüm 3.5.Projenin System.Core.dll referansı vardır ve bir using yönergesi (C#) veya Imports deyimi (Visual Basic) varsayılan olarak System.Linq ad.C# projeleri, ekleme bir using yönergesi System.IO ad alanı.

  • Projenize bu kodu kopyalayın.

  • Derlemek ve program çalıştırmak için F5 tuşuna basın.

  • Konsol penceresine çıkmak için herhangi bir tuşa basın.

Güçlü Programlama

Belge ve dosyalarınız birden çok türde içeriği üzerinde yoğun sorgu işlemleri için kullanmayı Windows Desktop Search altyapısı.

Ayrıca bkz.

Kavramlar

LINQ nesnelere

LINQ ve dosya dizinleri