LINQ to File Directories

LINQ to Files means writing LINQ queries to get files and directories in a system. By writing LINQ queries, we can quickly get file details like the file's name or size of file or content from the system directory without writing much code.

Syntax of LINQ to File Directories

Following is the syntax of writing LINQ queries on file directories to get the required files from available files in the folder.

 

C# Code

 

var files = from file in filedir.GetFiles()
select new { FileName = file.Name, FileSize = (file.Length / 1024) };

VB.NET Code

 

Dim files = From file In filedir.GetFiles() Select New With {.FileName = file.Name, .FileSize = (file.Length / 1024)}

If you observe the above syntax, we wrote the LINQ query to get files information from the “filedir” directory object.

Example of LINQ to File Directories

Following is the example of LINQ to Files to get files information from the file directory in the system.

 

C# Code

 

using System;
using System.IO;
using System.Linq;

namespace Linqtutorials
{
  class Program
  {
    static void Main(string[] args)
    {
      DirectoryInfo filedir = new DirectoryInfo(@"E:\Images");
      var files = from file in filedir.GetFiles()
      select new { FileName = file.Name, FileSize = (file.Length / 1024) + " KB" };
      Console.WriteLine("FileName" + "\t | " + "FileSize");
      Console.WriteLine("--------------------------");
      foreach (var item in files)
      {
        Console.WriteLine(item.FileName + "\t | " + item.FileSize);
      }
      Console.ReadLine();
    }
  }
}

VB.NET Code

 

Imports System.IO

Module Module1
Sub Main()
Dim filedir As New DirectoryInfo("D:\Images")
Dim files = From file In filedir.GetFiles() Select New With {.FileName = file.Name, .FileSize = (file.Length / 1024)}
Console.WriteLine("FileName" + vbTab & " | " + "FileSize")
Console.WriteLine("--------------------------")
For Each item In files
Console.WriteLine("{0}" + vbTab & " | " + "{1} KB", item.FileName, item.FileSize)
Next
Console.ReadLine()
End Sub
End Module

If you observe the above code, we used the LINQ query to get files information from the "D:\Images" directory in the system.

Result of LINQ to File Directories Example

Following is the result of the LINQ to Files example.

 

FileName              | FileSize
-----------------------------------
colorcombo.png        | 23 KB
logistics.png         | 5 KB
samplefile.png        | 5 KB

This is how we can use LINQ queries with file directories to get required data in c#, vb.net.