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

When you enter a directory name and click the List Files button, the following code uses Language Integrated Query (LINQ) to list the files in the directory together with their sizes.

// 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 uses a FileInfo object to range over the files in the directory.

The query's orderby clause sorts the files by their lengths with the largest coming first. Note that the lengths are in bytes.

The query's select clause selects each file's name and its length converted into a string by the ToFileSizeApi extension method. That method converts the size in bytes into a string in KB, MB, etc. For more information on this extension method, see Format a number of bytes in KB, MB, GB, and so forth in C#.

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

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.