0

Is it possible to get only list of Excel filenames (like : 2021070701.CSV) in a folder ?

I'm getting the full path of the .csv excel when I use this "Directory.GetFiles" but I want to filter only excel filename with extension (like : 2021070701.CSV)

I used "FileInfo fi = new FileInfo();" but I didn't get the proper solution.

         public static void getExcelFileName()
        {

            string[] filename = Directory.GetFiles(@"C:\Users\Ashok 
                  Kumar\OneDrive\Desktop\Ashok\MarketPrice\NSE\Futures\Live", "*.csv");

            foreach (var item in filename)
            {
                Console.WriteLine(item);
            }
        }

This is the path I'm getting

Full Path of the excel

Help me out form this I'm new to coding.

Ashok
  • 25
  • 5
  • 2
    System.IO.Path class can get you the file name from the path. [Path.GetFileName(string)](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=net-5.0#system-io-path-getfilename(system-string)) – hijinxbassist Jul 12 '21 at 17:14
  • Take a look at [Path.GetFileName()](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=net-5.0) – Innat3 Jul 12 '21 at 17:16
  • i think theres also a filter for look up only ur wanted files, if not u can do in ur foreach loop the extension check, theres a method for it and ur idee should tell u – StefanBD Jul 12 '21 at 17:18
  • Does this answer your question? [How to get file name from a path in c#](https://stackoverflow.com/questions/42742457/how-to-get-file-name-from-a-path-in-c-sharp) – Orace Jul 12 '21 at 19:31

2 Answers2

1

You can use the GetFileNameWithoutExtension() method from the Path class to get the names of your files.

public static void getExcelFileName()
        {

            string[] filename = Directory.GetFiles(@"C:\Users\Ashok 
                  Kumar\OneDrive\Desktop\Ashok\MarketPrice\NSE\Futures\Live", "*.csv");

            foreach (var item in filename)
            {
                Console.WriteLine(Path.GetFileNameWithoutExtension(item));
            }
        }
Andrei Solero
  • 802
  • 1
  • 4
  • 12
0

Sure, you can call Path.GetFileName(string) which returns exactly what you're asking for!

        public static void getExcelFileName()
        {
            string[] filesPaths = Directory.GetFiles(@"C:\Users\Ashok Kumar\OneDrive\Desktop\Ashok\MarketPrice\NSE\Futures\Live",
                "*.csv");

            foreach (var filePath in filesPaths)
            {
                Console.WriteLine(Path.GetFileName(filePath));
            }
        }
OnZi12
  • 86
  • 3