C# - How to remove Extension from File Name in C#

Scenario : Download Script

You are working as C# or dot net developer, You need to read the file names from a folder and then remove the extension from file names.

The file extensions can be of different lengths, such as .txt is only three characters but .xlsx is 4 character extension. We can't simply remove last 3 or 4 characters from file name to get only file name.

As the extension are added after dot (.) , if we can find the position of dot and remove the string from there, we will be left with file name only. 

There could be special scenario when file name can have dot (.) as part of file name. That means that to find the extension's dot, we need to find the last dot in file name.

Here are some sample files I have in C:\Source folder.

How to remove extension from file name in C# 

I wrote below C# Console Application, this will read the file names from a folder. We will use Substring Method with LastIndexOf Method to remove extension from each file name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//add namespace
using System.IO;

namespace TechBrothersIT.com_CSharp_Tutorial
{
    class Program
    {
        static void Main(string[] args)
        {
            //Source Folder path for files
            string Folderpath = @"C:\Source\";

            //Reading file names one by one
            string[] fileEntries = Directory.GetFiles(Folderpath, "*.*");
            foreach (string FileName in fileEntries)
            {

                //declare  a variable and get file name only in it from FileName variable
                string FileNameOnly = FileName.Substring(0, FileName.LastIndexOf("."));

                //Print the values for FileName and FileNameOnly variables
                Console.WriteLine("FileName variable Value :" + FileName);
                Console.WriteLine("FileNameOnly variable Value :" + FileNameOnly);
                Console.ReadLine();

            }
        }
    }
}


Here are the output after and before removing the extension from file name in C#. 
How to remove extension from files in C#



No comments:

Post a Comment