HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMajor

How to remove file extension using C#?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fileextensionremoveusinghow

Problem

I am trying to remove file extension of a file with many dots in it:

string a = "asdasdasd.asdas.adas.asdasdasdasd.edasdasd";

string b = a.Substring(a.LastIndexOf('.'), a.Length - a.LastIndexOf('.'));

string c = a.Replace(b, "");

Console.WriteLine(c);


Is there any better way of doing this?

Solution

If you can, just use Path.GetFileNameWithoutExtension


Returns the file name of the specified path string without the extension.

Path.GetFileNameWithoutExtension("asdasdasd.asdas.adas.asdasdasdasd.edasdasd");


With one line of code you can get the same result.

If you want to create one by yourself, why not just use this?

int index = a.LastIndexOf('.');
b = index == -1 ? a : a.Substring(0, index);


P.S Special thanks to @Anthony and @CompuChip to point me out some mistake i done, bad day maybe.

You take everything which comes from 0 (the start) to the last dot which means the start of the extension

Code Snippets

Path.GetFileNameWithoutExtension("asdasdasd.asdas.adas.asdasdasdasd.edasdasd");
int index = a.LastIndexOf('.');
b = index == -1 ? a : a.Substring(0, index);

Context

StackExchange Code Review Q#46559, answer score: 23

Revisions (0)

No revisions yet.