简体   繁体   中英

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 )

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

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.

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

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

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

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)

如果文件名包含目录并且您不需要丢失目录:

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

try this,

string FileNameAndExtension =  "bılah bılah.pdf";
string FileName = FileNameAndExtension.Split('.')[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.

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

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

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM