0 0 Votes

C#/.NET: Change File Extension

Question by CSchaf | 04/09/2014 at 12:49

How is it possible to change the file extension of one file quickly and easily in C# (C-Sharp, .NET Framework)?

The file is present together with its complete path as a string, nevertheless, if possible, I would like to refrain from cumbersome string replacements (I have tried to do that but there were only problems, for example, if the extension is part of the filename).

Is there are any simple possibility for that in C#?

ReplyPositiveNegative

Stefan Trost

Show Profile | Message
Avatar
2Best Answer
2 Votes

You can just use the method Path.ChangeExtension from System.IO.

Let's have a look at a simple example:

string oldname = @"C:/MyFile.dat";
string newname = Path.ChangeExtension(oldname, ".txt");

Here, we are changing the string "C:/MyFile.dat" to "C:/MyFile.txt".

However, this only changes the string and not a real file. If you also want to rename an existing file on your hard drive, you can afterwards use the function File.Move from System.IO. You can pass the old and the new file name including the path to this function:

File.Move(oldname, newname);

Note: When passing a string without file extension to Path.ChangeExtension, the file extension is just appended to the string.
04/09/2014 at 14:00

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.