LINQ & Files in C#.Net

How to use LINQ query to get, short, size of files, files by extension, file with Maxi and Min in size, by created date of files in a directory in c#.

 In today's article I will show how you can perform files operation like get all the files in a folder using LINQ, filter file by extension of the files, short file by date, get all the file author details and file creation date.

So here we will use .NET Core with C#.Net. Let's start by creating a .NET core console application with C#.Net. After creating console application, create a folder and add few different type of files. 

Files in Folder in C#.Net

Here in above folder, I have taken few files if different type like .docx, .xlsx, .jpeg, .txt. By keeping these files as reference, we will perform different operation using LINQ on files in C#.Net.

How To Get all Files by LINQ in C#.Net?

string folderPath = "D:\\DemoRepo\\Myfolder";
if (Path.Exists(folderPath))
{
    DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
    var fileList = from d in directoryInfo.GetFiles()
                   select d;
    foreach (var file in fileList)
    {
        Console.WriteLine(file.FullName);
    }
}
In above code I have taken a variable where in this variable I have stored the local folder path. After that I have validated whether the path exists or not. If provided path exists on that case I have crated the object for the DirectoryInfo class, and passed the folder or directory path. Please check the below LINQ query which I have used to get query all the files. 
 var fileList = from d in directoryInfo.GetFiles()
                   select d;
After that I have used foreach loop to get the files and displayed.

How To Get all Files by LINQ in C#.Net?

How to Filter Files by Extension by LINQ in C#.Net?

string folderPath = "D:\\DemoRepo\\Myfolder";
string[] fileExt = { ".txt", ".docx", ".xlsx", ".jpg" };
if (Path.Exists(folderPath))
{
    DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
    foreach (string ext in fileExt)
    {
        Console.WriteLine("File Extention: " + ext);
        var fileList = from d in directoryInfo.GetFiles()
                       where d.Extension == ext
                       select d;
        foreach (var file in fileList)
        {
            Console.WriteLine(file.FullName);
        }
    }
}
In above code I have taken the folder location which is having folder location. After defining the folder location, I have taken an array of string, in this I have taken the file extensions. After that validation for the folder exists or not. if it exists on that case, I have created object for DirectoryInfo to and passed the folder path. 

After reading the directory I have applied foreach loop of the array having extension now please check the LINQ query there directoryInfo.GetFiles() is used for getting all the files in LINQ and in where clause filter of file extension has been applied. 
        var fileList = from d in directoryInfo.GetFiles()
                       where d.Extension == ext
                       select d;
Ass per extension of the file name has been displayed.

How to Filter Files by Extension by LINQ in C#.Net?

How to Get File Count by LINQ in C#.Net?

string folderPath = "D:\\DemoRepo\\Myfolder";
if (Path.Exists(folderPath))
{
    DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
    var fileCount = (from d in directoryInfo.GetFiles()
                     select d).Count();
    Console.WriteLine("Total File Count: " + fileCount);
}
In above to get the count of the files I have created object of the  DirectoryInfo to get folder detail. after that check the LINQ query where I have used method directoryInfo.GetFiles() to get all the files in directory and after that I have applied Count () method to get total count of files available in it.

How to Get File Count by LINQ in C#.Net?

How to Get File Count by Extension by LINQ in C#.Net?

string folderPath = "D:\\DemoRepo\\Myfolder";
if (Path.Exists(folderPath))
{
    DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
    var fileCountList = (from d in directoryInfo.GetFiles()
                         group d by d.Extension into fc
                         select new { count = fc.Count(), Ext = fc.Key });
    foreach (var file in fileCountList)
    {
        Console.WriteLine(string.Format("Count for file extension{0}: {1} ", file.Ext, file.count));
    }
}

The above code will provide all the file count as per as per extension. Here I have used LINQ Group By with C#.Net to calculate the file count available as per extension.  Now let's run the code to check the output. Beffore that let put a break point and check the output return by the LINQ query used for counting the file by extension.

LINQ file file count by extention in C#.Net

Here we can check see the extension and the count of the file. Press F5 to check the final output.

How to Get File Count by Extension by LINQ in C#.Net?

How to Get File Created Date by LINQ in C#.Net?

string folderPath = "D:\\DemoRepo\\Myfolder";
if (Path.Exists(folderPath))
{
    DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
    var fileList = from d in directoryInfo.GetFiles()
                   select new { d.Name, d.CreationTime };
    foreach (var file in fileList)
    {
        Console.WriteLine(string.Format("{0} Created Date:{1} ", file.Name, file.CreationTime));
    }
}
In above code I have first take validated the path of directory exists or not. After that used DirectoryInfo to read the directory detail. Now in LINQ query by C#.Net there I have selected file name and file creation date. Here we are making a list collection by file name with the date. Now used  Console.WriteLine to display the detail. Now let's put a break point and check the output.  

List of File CreatedDate by LINQ in C#.Net?
In above view we can see we are able to get all the files available in the directory wit there created date time. Now press F5 to check the output.

How to Get File Created Date by LINQ in C#.Net?

How to Short File by Created Date by LINQ in C#.Net?

string folderPath = "D:\\DemoRepo\\Myfolder";
if (Path.Exists(folderPath))
{
    DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
    var fileList = directoryInfo.GetFiles().OrderBy(f => f.CreationTime).ToList();
    foreach (var file in fileList)
    {
        Console.WriteLine(string.Format("{0} Created Date:{1} ", file.Name, file.CreationTime));
    }
}
In above code check the LINQ query where I have applied OrderBy to short the file by Created datetime. To check the file short detail be date time I have user foreach loop to display the value.

How to Short File by Created Date by LINQ in C#.Net?

How to Short File by Name by LINQ in C#.Net?

string folderPath = "D:\\DemoRepo\\Myfolder";
if (Path.Exists(folderPath))
{
    DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
    var fileList = directoryInfo.GetFiles().OrderBy(f => f.Name).ToList();
    foreach (var file in fileList)
    {
        Console.WriteLine(string.Format("{0}", file.Name));
    }
}
In above code check the LINQ query where I have used the OrderBy method to short the file ascending order after  directoryInfo.GetFiles() name. After getting the file list to display used the foreach loop.

How to Short File by Name by LINQ in C#.Net?

How to Get Files Size by LINQ In C#.Net?

string folderPath = "D:\\DemoRepo\\Myfolder";
if (Path.Exists(folderPath))
{
    DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
    var fileList = from d in directoryInfo.GetFiles()
                   where d.Length > 0
                   select d;
    foreach (var file in fileList)
    {
        Console.WriteLine(string.Format("{0} with size {1}", file.Name, file.Length));
    }
}

In above code after validating the folder path and reading the folder or directory information by DirectoryInfo class now check the written LINQ query where I have used GetFiles() to get all the file list available in directory or in the folder. in where clause I have applied condition select only those files whose file size is greater than zero. This where condition will all files whose size is more than zero. Now let's put break point and check the details. 

C# to get file size is not zero
Here we are getting the two files whose size is not zero. Now let's press F5 to check the final output.

How to Get Files Size by LINQ In C#.Net?

How to Get Largest file Of Folder by LINQ in C#.Net?

string folderPath = "D:\\DemoRepo\\Myfolder";
if (Path.Exists(folderPath))
{
    DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
    var filewithMax = (from d in directoryInfo.GetFiles()
                       where d.Length > 0
                       select d).OrderByDescending(x=>x.Length).FirstOrDefault();
    Console.WriteLine(string.Format("File with Max size \nName:{0} \nSize:{1} ", filewithMax.Name, filewithMax.Length));
}
In above code I have taken the path of the folder in a variable, after validating the folder path I have used DirectoryInfo class object to get the file list. To get the file with max size first I have suser OrderByDescending to short the files in descending order by file size and used FirstOrDefault to take top value. Here I have filtered the file whose length is zero by applying in where clause in LINQ query. The return file detail will be the file with max in size. Now let's put a break point and check the output.
File with max size in c#
Here in above code, we can see the file win max size we have received. Now let's press F5 to complete the execution. 

How to Get Largest file Of Folder by LINQ in C#.Net?

How to Get Smallest file Of Folder by LINQ in C#.Net?

string folderPath = "D:\\DemoRepo\\Myfolder";
if (Path.Exists(folderPath))
{
    DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
    var fileWithMin = (from d in directoryInfo.GetFiles()
                       where d.Length > 0
                       select d).OrderBy(x=>x.Length).FirstOrDefault();
    Console.WriteLine(string.Format("File with Min size \nName:{0} \nSize:{1} ", fileWithMin.Name, fileWithMin.Length));
}
In above code first I have arrange the files in ascending (OrderBy) with their size by using length, and taken the top value by using FirstOrDefault. Now let's run the code to check the output. 

How to Get Smallest file Of Folder by LINQ in C#.Net?

Post a Comment