Aracılığıyla paylaş


Nasıl yapılır: sorgu için en büyük dosya veya dosyaların bir dizin ağacında (LINQ)

Bu örnekte, dosyanın bayt cinsinden boyutu ile ilgili beş sorguları gösterilmektedir:

  • Bayt olarak en büyük dosya boyutu nasıl alınır.

  • En küçük dosya boyutunu bayt cinsinden boyutu nasıl alınır.

  • Nasıl almak FileInfo belirtilen kök klasörünün altında bir veya daha fazla klasörlerden en büyük veya en küçük dosya nesnesi.

  • 10 Büyük dosyaları gibi bir dizi nasıl alınır.

  • Sipariş dosyaları belirtilen boyuttan daha küçük dosyaları göz ardı ediliyor, dosya boyutunu bayt cinsinden dayanarak gruplara nasıl.

Örnek

Aşağıdaki örnek, nasıl sorgulanacağını ve dosya boyutunu bayt cinsinden bağlı Grup dosyaları göster beş ayrı sorguları içerir.Diğer bazı özelliğinde, sorgunun temel amacıyla bu örnekleri kolayca değiştirebileceğiniz FileInfo nesne.

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
class QueryBySize
{
    static void Main(string[] args)
    {
        QueryFilesBySize();
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

    private static void QueryFilesBySize()
    {
        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);

        //Return the size of the largest file
        long maxSize =
            (from file in fileList
             let len = GetFileLength(file)
             select len)
             .Max();

        Console.WriteLine("The length of the largest file under {0} is {1}",
            startFolder, maxSize);

        // Return the FileInfo object for the largest file
        // by sorting and selecting from beginning of list
        System.IO.FileInfo longestFile =
            (from file in fileList
             let len = GetFileLength(file)
             where len > 0
             orderby len descending
             select file)
            .First();

        Console.WriteLine("The largest file under {0} is {1} with a length of {2} bytes",
                            startFolder, longestFile.FullName, longestFile.Length);

        //Return the FileInfo of the smallest file
        System.IO.FileInfo smallestFile =
            (from file in fileList
             let len = GetFileLength(file)
             where len > 0
             orderby len ascending
             select file).First();

        Console.WriteLine("The smallest file under {0} is {1} with a length of {2} bytes",
                            startFolder, smallestFile.FullName, smallestFile.Length);

        //Return the FileInfos for the 10 largest files
        // queryTenLargest is an IEnumerable<System.IO.FileInfo>
        var queryTenLargest =
            (from file in fileList
             let len = GetFileLength(file)
             orderby len descending
             select file).Take(10);

        Console.WriteLine("The 10 largest files under {0} are:", startFolder);

        foreach (var v in queryTenLargest)
        {
            Console.WriteLine("{0}: {1} bytes", v.FullName, v.Length);
        }


        // Group the files according to their size, leaving out
        // files that are less than 200000 bytes. 
        var querySizeGroups =
            from file in fileList
            let len = GetFileLength(file)
            where len > 0
            group file by (len / 100000) into fileGroup
            where fileGroup.Key >= 2
            orderby fileGroup.Key descending
            select fileGroup;


        foreach (var filegroup in querySizeGroups)
        {
            Console.WriteLine(filegroup.Key.ToString() + "00000");
            foreach (var item in filegroup)
            {
                Console.WriteLine("\t{0}: {1}", item.Name, item.Length);
            }
        }
    }

    // This method is used to swallow the possible exception
    // that can be raised when accessing the FileInfo.Length property.
    // In this particular case, it is safe to swallow the exception.
    static long GetFileLength(System.IO.FileInfo fi)
    {
        long retval;
        try
        {
            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;
    }

}

Bir veya daha fazla tamamlamak dönmek için FileInfo nesneler, sorguyu ilk denetleyeceğini her biri veri kaynağı ve bunların uzunluk özelliği değerine göre sıralayabilirsiniz.Sonra tek tek ya da en büyük uzunlukları başta dönebilirsiniz.Use First listedeki ilk öğe verilecek.Use Take<TSource> ilk dönmek için n öğe sayısı.Listenin başında küçük öğeleri yerleştirmek için azalan sıralama düzeni belirtin.

Sorgu burada bir dosya silindi başka bir iş parçacığı üzerinde bu yana zaman dönemindeki durumda yükseltilmiş olası durum kullanmak için dosya boyutunu bayt cinsinden elde etmek için ayrı bir yöntemini çağıran FileInfo nesnenin oluşturulduğu çağrısında GetFiles.Hatta aracılığıyla FileInfo nesne zaten oluşturuldu, özel durum ortaya çıkabilir çünkü bir FileInfo yenilemek nesne çalýþýlýr kendi Length en geçerli boyutunu bayt cinsinden özelliği erişildiğinde ilk kez kullanarak özellik.Bu işlem sorgu dışında bir try-catch bloğu içinde yerleştirerek, biz yan etkilere yol açabilecek sorgularda işlemlerini engelleme kuralı uygulayın.Genel olarak, çok dikkatli özel durumlar, tüketen, uygulama bilinmeyen bir durumda sol değil emin olunmalıdır.

Kod Derleniyor

  • Oluşturma bir Visual Studio hedefleyen 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) System.Linq ad alanı varsayılan olarak.

  • 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