Getting file names without extensions

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)


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


This solution also prevents the addition of a trailing comma.

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

I dislike the DirectoryInfo, FileInfo for this scenario.

DirectoryInfo and FileInfo collect more data about the folder and the files than is needed so they take more time and memory than necessary.