33

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
  • 8,358
  • 12
  • 41
  • 68
Glory Raj
  • 17,397
  • 27
  • 100
  • 203

5 Answers5

54

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

string filenameWithoutPath = Path.GetFileName(filename);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 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
12

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,896
  • 9
  • 51
  • 66
3

Try GetFileName() method:

Path.GetFileName(filename);
Community
  • 1
  • 1
ojlovecd
  • 4,812
  • 1
  • 20
  • 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
1

Linq is good

Directory.GetFiles( dir ).Select( f => Path.GetFileName( f ) ).ToArray();

Garrod Ran
  • 318
  • 3
  • 5