Hi @Anjali Agarwal , Welcome to Microsoft Q&A,
You can compare file extensions using the String.Equals method and specify StringComparison.OrdinalIgnoreCase to ignore case.
using System;
using System.IO;
using System.Linq;
namespace xxx
{
internal class Program
{
static void Main(string[] args)
{
string directoryPath = @"C:\Users\Administrator\Desktop\";
DirectoryInfo di = new DirectoryInfo(directoryPath);
try
{
var myFiles = (from f in di.GetFiles()
where f.Extension.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || f.Extension.Equals(".png", StringComparison.OrdinalIgnoreCase)
orderby f.LastWriteTime descending
select f).ToList();
if (myFiles.Any())
{
Console.WriteLine("Matching files found:");
foreach (var file in myFiles)
{
Console.WriteLine($" {file.FullName}");
}
}
else
{
Console.WriteLine("No matching files found.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
Console.ReadLine();
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.