344

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)

14 Answers 14

598

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

5
  • 10
    And to get the extension (to add later for example) use: Path.GetExtension(fileName);
    – Justin
    Commented Mar 27, 2014 at 9:08
  • 5
    @Juzzz That's handy if you're working with a bare string, but if you already have a FileInfo object, there's no need to bother with Path. FileInfo already provides the "Extension" property for the purpose.
    – jmbpiano
    Commented Jul 28, 2015 at 14:42
  • I got the error " 'builder' does not exist in the current context ". I added 'system.Text' but still got same error. What is the reason?
    – ffttyy
    Commented Jan 27, 2016 at 19:52
  • @ffttyy builder will be an instance of StringBuilder in the OP's code. It's just an example use of GetFileNameWithoutExtension - you'll likely do better writing your own code that calls it.
    – Rup
    Commented Jan 28, 2016 at 9:47
  • 10
    One gotcha to note here is that if your file contains a double extension, GetFileNameWithoutExtension only removes the end extension. For example, the filename example.es6.js will become example.es6 Commented Mar 1, 2016 at 12:01
54

Use Path.GetFileNameWithoutExtension().

1
  • Note that the Path.GetFileNameWithoutExtension is not best way as it checks for invalid path chars and try to extract the DirectorySeparatorChar, AltDirectorySeparatorChar or VolumeSeparatorChar in a loop which seems not necessary for file names (not full path's)! Commented Jun 3, 2019 at 5:09
24

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.

6
  • 2
    +1. I also prefer Directory.GetFiles over DirectoryInfo.GetFiles anyday, if all I want is file names.
    – Yogesh
    Commented Jan 27, 2011 at 8:30
  • I like this because String.Join, LINQ, no StringBuilder.
    – Csaba Toth
    Commented Nov 8, 2015 at 19:40
  • If you take a look at the source code. FileInfo's constructor is very light weight. And all the information you see is done through properties. They are only gathered when you call them
    – fjch1997
    Commented Oct 19, 2017 at 1:05
  • @fjch1997 - The constructor does call Path.GetFileName and checks permissions. So that seems a bit redundant.
    – Emond
    Commented Oct 19, 2017 at 3:44
  • @ErnodeWeerd FileIOPermission does not check permission against the ACL. instead it's some kind of mechanism in .NET to check permission for partially trusted code. So, it shouldn't make any actual IO call. How much it impacts performance? i can't say without testing. But i assume it's not that great
    – fjch1997
    Commented Oct 19, 2017 at 19:20
22
Path.GetFileNameWithoutExtension(file);

This returns the file name only without the extension type. You can also change it so you get both name and the type of file

 Path.GetFileName(FileName);

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

3
  • Thanks, the best answer is always the shortest answer. Commented May 31, 2019 at 17:29
  • But in this case it's just a copy of the accepted answer, 5 years later...
    – Grim
    Commented Jun 27, 2021 at 16:39
  • This is incorrect. 'Path.GetFileName(FileName);' "Returns the file name and extension of a file path represented by a read-only character span." I used the source that is stated above. msdn.microsoft.com/en-us/library/system.io.path(v=vs.110).aspx
    – Lynn
    Commented Sep 13, 2022 at 21:23
12

Use Path.GetFileNameWithoutExtension. Path is in System.IO namespace.

10

FileInfo knows its own extension, so you could just remove it

fileInfo.Name.Replace(fileInfo.Extension, "");
fileInfo.FullName.Replace(fileInfo.Extension, "");

or if you're paranoid that it might appear in the middle, or want to microoptimize:

file.Name.Substring(0, file.Name.Length - file.Extension.Length)
7

As an additional answer (or to compound on the existing answers) you could write an extension method to accomplish this for you within the DirectoryInfo class. Here is a sample that I wrote fairly quickly that could be embellished to provide directory names or other criteria for modification, etc:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace DocumentDistributor.Library
{
    public static class myExtensions
    {
        public static string[] GetFileNamesWithoutFileExtensions(this DirectoryInfo di)
        {
            FileInfo[] fi = di.GetFiles();
            List<string> returnValue = new List<string>();

            for (int i = 0; i < fi.Length; i++)
            {
                returnValue.Add(Path.GetFileNameWithoutExtension(fi[i].FullName)); 
            }

            return returnValue.ToArray<string>();
         }
    }
}

Edit: I also think this method could probably be simplified or awesome-ified if it used LINQ to achieve the construction of the array, but I don't have the experience in LINQ to do it quickly enough for a sample of this kind.

Edit 2 (almost 4 years later): Here is the LINQ-ified method I would use:

public static class myExtensions
{
    public static IEnumerable<string> GetFileNamesWithoutExtensions(this DirectoryInfo di)
    {
        return di.GetFiles()
            .Select(x => Path.GetFileNameWithoutExtension(x.FullName));
    }
}
5

if file name contains directory and you need to not lose directory:

fileName.Remove(fileName.LastIndexOf("."))
3

try this,

string FileNameAndExtension =  "bılah bılah.pdf";
string FileName = FileNameAndExtension.Split('.')[0];
2
  • Attention! Not working with filenames, that have an additional point...
    – SiL3NC3
    Commented Mar 4, 2022 at 22:40
  • yep, in this case, needs to be split by the last dot only
    – Ali CAKIL
    Commented Mar 12, 2022 at 7:12
2

It seems messy to use Path.GetFileNameWithoutExtension in the case you already have a FileInfo object.

So you might take advantage of the fact FileInfo.Extension is part of FileInfo.Name to do a simple string operation, and just remove the end of the string:

DirectoryInfo di = new DirectoryInfo(currentDirName);
FileInfo[] smFiles = di.GetFiles("*.txt");
foreach (FileInfo fi in smFiles)
{
    var name = fileInfo.Name.Remove(fileInfo.Name.Length - fileInfo.Extension.Length);
    builder.Append(name);
    builder.Append(", ");
    ...
}
0

Just for the record:

DirectoryInfo di = new DirectoryInfo(currentDirName);
FileInfo[] smFiles = di.GetFiles("*.txt");
string fileNames = String.Join(", ", smFiles.Select<FileInfo, string>(fi => Path.GetFileNameWithoutExtension(fi.FullName)));

This way you don't use StringBuilder but String.Join(). Also please remark that Path.GetFileNameWithoutExtension() needs a full path (fi.FullName), not fi.Name as I saw in one of the other answers.

0

Below is my code to get a picture to load into a PictureBox and Display a Picture name in to a TextBox without Extension.

private void browse_btn_Click(object sender, EventArgs e)
    {
        OpenFileDialog Open = new OpenFileDialog();
        Open.Filter = "image files|*.jpg;*.png;*.gif;*.icon;.*;";
        if (Open.ShowDialog() == DialogResult.OK)
        {
            imageLocation = Open.FileName.ToString();
            string picTureName = null;
            picTureName = Path.ChangeExtension(Path.GetFileName(imageLocation), null);

            pictureBox_Gift.ImageLocation = imageLocation;
            GiftName_txt.Text = picTureName.ToString();
            Savebtn.Enabled = true;
        }
    }
0

You can make an extension method on FileInfo:

public static partial class Extensions
{
    public static string NameWithoutExtension(this FileInfo fi) => Path.GetFileNameWithoutExtension(fi.Name);
}

Answering the original question:

new DirectoryInfo(dirPath).EnumerateFiles().Select(file => file.NameWithoutExtension());

Say you want to get all files with a certain name:

new DirectoryInfo(dirPath).EnumerateFiles().Where(file => file.NameWithoutExtension() == fileName).FullName;
-6
using System;

using System.IO;

public class GetwithoutExtension
{

    public static void Main()
    {
        //D:Dir dhould exists in ur system
        DirectoryInfo dir1 = new DirectoryInfo(@"D:Dir");
        FileInfo [] files = dir1.GetFiles("*xls", SearchOption.AllDirectories);
        foreach (FileInfo f in files)
        {
            string filename = f.Name.ToString();
            filename= filename.Replace(".xls", "");
            Console.WriteLine(filename);
        }
        Console.ReadKey();

    }

}
4
  • 5
    You don't seem to be aware that there is already a Framework class that does this for you. Commented Sep 28, 2012 at 6:22
  • 3
    Also, if someone named their files "Current.XLSFiles.xls" this is going to cause REAL problems. Commented Apr 24, 2014 at 12:24
  • @TomPadilla why would this cause problems?
    – Luke101
    Commented Dec 25, 2019 at 4:13
  • Because this method would present "Current.files"as the file name. Because every instance of ".xls" would be replaced with"", including ones in the middle of the name. Commented Dec 25, 2019 at 18:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.