When getting file names in a certain folder:
DirectoryInfo di = new DirectoryInfo(currentDirName); FileInfo[] smFiles = di.GetFiles("*.txt"); foreach (FileInfo fi in smFiles) { builder.Append(fi.Name); builder.Append(", "); ... }
fi.Name
gives me a file name with its extension: file1.txt
, file2.txt
, file3.txt
.
How can I get the file names without the extensions? (file1
, file2
, file3
)
Make Sure the File Doesn't Have an Extension You can check the file extension from the Type column in Windows file explorer. Alternatively, you could right-click on the file and select Properties. You'll see the Type of file in the General tab of file properties.
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 extract the file extension of a filename string using the os. path. splitext method. It splits the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period.
You can use Path.GetFileNameWithoutExtension
:
foreach (FileInfo fi in smFiles) { builder.Append(Path.GetFileNameWithoutExtension(fi.Name)); builder.Append(", "); }
Although I am surprised there isn't a way to get this directly from the FileInfo
(or at least I can't see it).
Use Path.GetFileNameWithoutExtension()
.
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