[c#] 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)

This question is related to c# .net

The answer is



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

    }

}

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)

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.


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


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;
        }
    }

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.


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


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));
    }
}

try this,

string FileNameAndExtension =  "bilah bilah.pdf";
string FileName = FileNameAndExtension.Split('.')[0];

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

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