Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I just get the base filename from this C# code?

Tags:

c#

I have the following code:

string[] files = Directory.GetFiles(@"C:\Notes", "*.txt", SearchOption.TopDirectoryOnly);
foreach(string file in files)

When I check the contents of file it has the directory path and extension. Is there a way I can just get the filename out of that?

like image 954
Jason Avatar asked Aug 09 '11 13:08

Jason


People also ask

How do I get the filename from the file path?

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.

How do I return only file names from the find command?

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"

What is base file name?

The basename is the final rightmost segment of the file path; it is usually a file, but can also be a directory name. Note: FILE_BASENAME operates on strings based strictly on their syntax. The Path argument need not refer to actual or existing files.

How do I get filenames without an extension in Unix?

If you want to retrieve the filename without extension, then you have to provide the file extension as SUFFIX with `basename` command. Here, the extension is “. txt”.


2 Answers

You can use the FileInfo class:

FileInfo fi = new FileInfo(file);
string name = fi.Name;

If you want just the file name - quick and simple - use Path:

string name = Path.GetFileName(file);
like image 79
Evan Mulawski Avatar answered Oct 26 '22 23:10

Evan Mulawski


You can use the following method: Path.GetFileName(file)

like image 36
iamkrillin Avatar answered Oct 26 '22 23:10

iamkrillin