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?
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.
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"
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.
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”.
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);
You can use the following method: Path.GetFileName(file)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With