Getting file names without extensions

rem picture rem · Jan 26, 2011 · Viewed 271.2k times · Source

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)

Answer

Rup picture Rup · Jan 26, 2011

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