rem
rem

Reputation: 17045

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)

Upvotes: 347

Views: 375095

Answers (14)

Mr. Boy
Mr. Boy

Reputation: 63710

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(", ");
    ...
}

Upvotes: 2

trinalbadger587
trinalbadger587

Reputation: 2109

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;

Upvotes: 1

user1852100
user1852100

Reputation: 1

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

Upvotes: 0

Ali CAKIL
Ali CAKIL

Reputation: 428

try this,

string FileNameAndExtension =  "bılah bılah.pdf";
string FileName = FileNameAndExtension.Split('.')[0];

Upvotes: 3

Papuashu
Papuashu

Reputation: 69

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.

Upvotes: 0

Omid.Hanjani
Omid.Hanjani

Reputation: 1522

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

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

Upvotes: 5

drzaus
drzaus

Reputation: 24994

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)

Upvotes: 10

Chong Ching
Chong Ching

Reputation: 445

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

Upvotes: 23

Emond
Emond

Reputation: 50672

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.

Upvotes: 24

Joel Etherton
Joel Etherton

Reputation: 37523

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

Upvotes: 7

Rup
Rup

Reputation: 34408

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

Upvotes: 605

user1621648
user1621648

Reputation:

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

    }

}

Upvotes: -6

Pradeep
Pradeep

Reputation: 3276

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

Upvotes: 12

Related Questions