Coder Perfect

Obtaining file names that do not have extensions


When looking for file names in a specific folder, use the following formula:

DirectoryInfo di = new DirectoryInfo(currentDirName);
FileInfo[] smFiles = di.GetFiles("*.txt");
foreach (FileInfo fi in smFiles)
    builder.Append(", ");

file1.txt, file2.txt, and file3.txt are the file names that fi.Name returns.

How can I get the file names without the extensions? (file1, file2, file3)

Asked by rem

Solution #1

You can make use of Path. GetFileNameWithoutExtension:

foreach (FileInfo fi in smFiles)
    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).

Answered by Rup

Solution #2

Use Path.GetFileNameWithoutExtension().

Answered by Marcel Gheorghita

Solution #3

This method also eliminates the need for a trailing comma.

var filenames = String.Join(
                    ", ",
                    Directory.GetFiles(@"c:\", "*.txt")
                       .Select(filename => 

For this circumstance, I loathe DirectoryInfo and FileInfo.

DirectoryInfo and FileInfo capture more information about the folder and files than is required, consuming more time and memory.

Answered by Emond

Solution #4


This method only returns the file name, not the extension type. You can also alter it so that you get both the file name and the file type.



Answered by Chong Ching

Solution #5

Make use of the path. GetFileNameWithoutExtension. Path is a member of the System.IO namespace.

Answered by Pradeep

Post is based on