340

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)

Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
rem
  • 16,745
  • 37
  • 112
  • 180

14 Answers14

581

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

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Rup
  • 33,765
  • 9
  • 83
  • 112
  • 10
    And to get the extension (to add later for example) use: Path.GetExtension(fileName); – Justin Mar 27 '14 at 09:08
  • 4
    @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 Jul 28 '15 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 Jan 27 '16 at 19:52
  • @ffttyy `builder` will be an instance of [`StringBuilder`](https://msdn.microsoft.com/en-us/library/system.text.stringbuilder(v=vs.110).aspx) 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 Jan 28 '16 at 09: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` – David Roberts Mar 01 '16 at 12:01
54

Use Path.GetFileNameWithoutExtension().

svick
  • 236,525
  • 50
  • 385
  • 514
Marcel Gheorghita
  • 1,853
  • 13
  • 19
  • 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)! – S.Serpooshan Jun 03 '19 at 05: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.

Emond
  • 50,210
  • 11
  • 84
  • 115
  • 2
    +1. I also prefer `Directory.GetFiles` over `DirectoryInfo.GetFiles` anyday, if all I want is file names. – Yogesh Jan 27 '11 at 08:30
  • I like this because String.Join, LINQ, no StringBuilder. – Csaba Toth Nov 08 '15 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 Oct 19 '17 at 01:05
  • @fjch1997 - The constructor does call Path.GetFileName and checks permissions. So that seems a bit redundant. – Emond Oct 19 '17 at 03: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 Oct 19 '17 at 19:20
  • Also to simplify you don't need a lamda expression. Just do this `Directory.GetFiles(@"C:\", "*.txt").Select(Path.GetFileNameWithoutExtension)` – iheartcsharp Nov 29 '17 at 14:48
21
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

Chong Ching
  • 425
  • 3
  • 7
  • Thanks, the best answer is always the shortest answer. – Ashraf Sada May 31 '19 at 17:29
  • But in this case it's just a copy of the accepted answer, 5 years later... – Grim Jun 27 '21 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. https://msdn.microsoft.com/en-us/library/system.io.path(v=vs.110).aspx – Lynn Sep 13 '22 at 21:23
12

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

Pradeep
  • 3,258
  • 1
  • 23
  • 36
9

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)
drzaus
  • 24,171
  • 16
  • 142
  • 201
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));
    }
}
Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
5

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

fileName.Remove(fileName.LastIndexOf("."))
Omid.Hanjani
  • 1,444
  • 2
  • 20
  • 29
3

try this,

string FileNameAndExtension =  "bılah bılah.pdf";
string FileName = FileNameAndExtension.Split('.')[0];
Ali CAKIL
  • 383
  • 5
  • 21
1

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(", ");
    ...
}
Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
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.

Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
Papuashu
  • 69
  • 5
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;
        }
    }
Dharman
  • 30,962
  • 25
  • 85
  • 135
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;
trinalbadger587
  • 1,905
  • 1
  • 18
  • 36
-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();

    }

}
Tisho
  • 8,320
  • 6
  • 44
  • 52