getting all the files with extension jpg and png

Anjali Agarwal 1,531 Reputation points
2023-11-22T03:33:53.6633333+00:00

I am trying to get the latest files from a directory. I have the LINQ statement that gets all the files:

    var myFile = (from f in di.GetFiles("*.jpg", "*.png")
                              orderby f.LastWriteTime descending
                              select f).First();

The issue is, its getting all the files that has upper case "JPG" and no .png files. How can i get all the lower case "*.jpg" and *.png" files from a directory.

Developer technologies | C#
{count} votes

Accepted answer
  1. Anonymous
    2023-11-22T06:42:50.68+00:00

    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();
            }
        }
    }
    
    

    User's image

    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.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.