Use LINQ to list files and file sizes in a directory in C#


When you enter a directory name and click the List Files button, the following code lists files and file sizes in the directory you entered in the text box.

// List the files in the selected directory and their sizes.
private void btnListFiles_Click(object sender, EventArgs e)
    // Search for the files.
    DirectoryInfo dirinfo = new DirectoryInfo(txtDirectory.Text);
    var fileQuery =
        from FileInfo fileinfo in dirinfo.GetFiles()
        orderby fileinfo.Length descending
        select String.Format("{0,10}  {1}",
            fileinfo.Length.ToFileSizeApi(), fileinfo.Name);

    // Display the result.
    lstFiles.DataSource = fileQuery.ToArray();

The code first creates a DirectoryInfo object representing the directory you entered.

The LINQ query’s from clause calls the DirectoryInfo object’s GetFiles method to get FileInfo object’s representing the files in the directory. It loops over those objects and selects their Length and Name properties, sorting the results by Length.

To make reading the file sizes easier, the select clause calls the ToFileSizeApi extension method. That method converts the size in bytes into a string in KB, MB, etc. For more information, see the post Format file sizes in KB, MB, GB, and so forth in C#.

The code finishes by converting the selected list of items into an array and setting a ListBox‘s DataSource property to it so the ListBox displays the values.

Download Example   Follow me on Twitter   RSS feed

This entry was posted in files, LINQ and tagged , , , , , , , , , , , , , . Bookmark the permalink.