Glory Raj
Glory Raj

Reputation: 17691

How to get file names from the directory, not the entire path

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)
{ }

Upvotes: 33

Views: 65815

Answers (5)

Garrod Ran
Garrod Ran

Reputation: 328

Linq is good

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

Upvotes: 2

ojlovecd
ojlovecd

Reputation: 4892

Try GetFileName() method:

Path.GetFileName(filename);

Upvotes: 3

Anders Marzi Tornblad
Anders Marzi Tornblad

Reputation: 19305

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)
{
    // ...
}

Upvotes: 12

Amit
Amit

Reputation: 11

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

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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

string filenameWithoutPath = Path.GetFileName(filename);

Upvotes: 54

Related Questions