C# - How to remove last X Characters from a string in C#

Scenario: Download Script

You are working as C# or dot net developer. You are writing a program in which you need to remove last x characters from a string.

To make it more real time problem, think about a scenario where you read text or csv files from a folder and then you need to remove the extension that is 4 characters (.csv or .txt).

The below code can be used to remove x characters from a string. Replace 4 with your number or characters you would like to remove.


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)
        {
            //declare FileName variable and save mytextfile.txt value
            string FileName = "mytextfile.txt";
            
            //create variable FileNameRemoved and save values after removing last 4 characters from FileName variable
            string FileNameRemoved = FileName.Substring(0, FileName.Length - 4);

            //Print the variable values
            Console.WriteLine("FileName Variable Value: " + FileName);
            Console.WriteLine("FileNameRemoved Variable Value: " + FileNameRemoved);
            

            //If we want to remove the last x characters and save in the same variable
            FileName = FileName.Remove(FileName.Length - 4, 1);
            Console.WriteLine("FileName Variable Value by using Remove and save to save variable: " + FileName);
            Console.ReadLine();

        }
    }
    }


Here is output after removing 4 characters from a string value in C#.
How to remove last x characters from string in C#

1 comment: