C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: Use ChangeExtension with string arguments such as ".txt". You can use null to remove the entire extension.
Instead: The method changes the path string's memory representation and returns a reference to the new string data.
And: After you receive the results of Path.ChangeExtension, you must write the new file to disk or move the old one.
Program: We call File.WriteAllText to write to the disk. We change the extension of a path to have ".html" instead of a ".txt" extension.
Info: You must specify the leading period, not just three letters, on the extension string.
C# program that changes path extension
using System.IO;
class Program
{
static void Main()
{
// The file name.
string path = "test.txt";
// Make sure the file exists.
File.WriteAllText(path, "Tutorial file");
// Change the path name to have a new extension in memory.
string changed = Path.ChangeExtension(path, ".html");
// Create file with the new extension name.
File.WriteAllText(changed, "Changed file");
}
}
Output
test.txt
test.html
Tip: If you pass an empty string "" to ChangeExtension, the period is not removed.
Note: Thanks to Pierre-Luc Gelinas for writing in with a bug report on this section.
C# program that removes extensions
using System;
using System.IO;
class Program
{
static void Main()
{
string original = "file.txt";
Console.WriteLine(Path.ChangeExtension(original, ""));
Console.WriteLine(Path.ChangeExtension(original, null));
}
}
Output
file.
file
Review: The method will throw various exceptions on invalid inputs. You may want to protect your program against these conditions.