32

I am using the below method to get the file names. But it returns the entire path and I don't want to get the entire path. I want only file names, not the entire path.

How can I get that only file names not the entire path

path= c:\docs\doc\backup-23444444.zip

string[] filenames = Directory.GetFiles(targetdirectory,"backup-*.zip");
foreach (string filename in filenames)
{ }
iknow
  • 6,507
  • 10
  • 30
  • 55
Glory Raj
  • 17,092
  • 26
  • 94
  • 188

4 Answers4

54

You could use the GetFileName method to extract only the filename without a path:

string filenameWithoutPath = Path.GetFileName(filename);
Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902
  • 1
    I have lot of files with same type how can i get list of files that filenames only contains that file name – Glory Raj Oct 12 '11 at 08:55
11

System.IO.Path is your friend here:

var filenames = from fullFilename
                in Directory.EnumerateFiles(targetdirectory,"backup-*.zip")
                select Path.GetFileName(fullFilename);

foreach (string filename in filenames)
{
    // ...
}
Anders Marzi Tornblad
  • 18,046
  • 9
  • 55
  • 65
2

Try GetFileName() method:

Path.GetFileName(filename);
Community
  • 1
  • 1
ojlovecd
  • 4,532
  • 1
  • 17
  • 22
1
You can use this, it will give you all file's name without Extension

    List<string> lstAllFileName = (from itemFile in dir.GetFiles()
                                               select Path.GetFileNameWithoutExtension(itemFile.FullName)).Cast<string>().ToList();
Amit
  • 11
  • 1