Coder Perfect

Obtaining file names that do not have extensions

Problem

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(fi.Name);
    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(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).

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 => 
                           Path.GetFileNameWithoutExtension(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

Path.GetFileNameWithoutExtension(file);

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.

 Path.GetFileName(FileName);

source:https://msdn.microsoft.com/en-us/library/system.io.path(v=vs.110).aspx

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 https://stackoverflow.com/questions/4804990/getting-file-names-without-extensions