Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting file names without extensions

Tags:

c#

.net

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)

like image 952
rem Avatar asked Jan 26 '11 13:01

rem


People also ask

What if a file doesn't have an extension?

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.

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”.

How do I separate filenames and extensions?

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.


Video Answer


2 Answers

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).

like image 153
Rup Avatar answered Oct 04 '22 09:10

Rup


Use Path.GetFileNameWithoutExtension().

like image 36
Marcel Gheorghita Avatar answered Oct 04 '22 10:10

Marcel Gheorghita