11 Vote

C#/.NET: Change File Extension

Question by CSchaf | Last update on 2024-01-01 | Created on 2014-09-04

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
2Best Answer4 Votes

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

Let's have a look at a simple example:

string name_old = @"C:/MyFile.dat";
string name_new = Path.ChangeExtension(name_old, ".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(name_old, name_new);

Note: When passing a string without file extension to Path.ChangeExtension, the file extension is just appended to the string.
Last update on 2024-01-01 | Created on 2014-09-04

ReplyPositive Negative
Reply

Related Topics

PHP: File Download Script

Tutorial | 0 Comments

Rename File to its Folder Name

Tutorial | 0 Comments

VirtualBox: Change Date and Time

Tutorial | 10 Comments

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 article on askingbox.com. That’s how it’s done.