Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
{ }
like image 300
Glory Raj Avatar asked Oct 12 '11 08:10

Glory Raj


People also ask

How can I find the filename without path?

To get a filename without the path, call the replace() method with the following regular expression: /^. *[\\\/]/ as the first parameter and an empty string as the second. The method will return a string that only contains the filename. Copied!

How can I get only file names?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);

How do I show only file names in Linux?

Normally find command will retrieve the filename and its path as one string. If you want to display only the filename, you can use basename command. find infa/bdm/server/source/path -type f -iname "source_fname_*. txt"


4 Answers

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

string filenameWithoutPath = Path.GetFileName(filename);
like image 182
Darin Dimitrov Avatar answered Oct 17 '22 07:10

Darin Dimitrov


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)
{
    // ...
}
like image 21
Anders Marzi Tornblad Avatar answered Oct 17 '22 08:10

Anders Marzi Tornblad


Try GetFileName() method:

Path.GetFileName(filename);
like image 2
ojlovecd Avatar answered Oct 17 '22 08:10

ojlovecd


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();
like image 1
Amit Avatar answered Oct 17 '22 08:10

Amit