LINQ to Files means writing LINQ queries to get files and directories in a system. By writing LINQ queries we can get file details like name of file or size of file or content from system directory easily without writing much code.
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 above syntax we written LINQ query to get files information from “filedir” directory object.
Following is the example of LINQ to Files to get files information from file directory in 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 LINQ query to get files information from "D:\Images" directory in sysytem.
Following is the result of 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.