Path.ChangeExtension
This modifies a path string
. It can, for example, change a file ending in a ".txt" extension to end in the ".html" extension.
Use ChangeExtension
with string
arguments such as ".txt". You can use null
to remove the entire extension. This makes it unnecessary to write custom string
methods.
First, we use Path.ChangeExtension
to change the extension of a path string
in the program's memory. The Path
class
does not access the disk or persist the change.
string
's memory representation and returns a reference to the new string
data.Path.ChangeExtension
, you must write the new file to disk or move the old one.File.WriteAllText
to write to the disk. We change the extension of a path to have ".html" instead of a ".txt" extension.string
.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"); } }test.txt test.html
Remove
extensionWe can remove the extension by providing null
. Because the Path
class
has no RemoveExtension
method, providing null
is the clearest way to remove the extension.
string
"" to ChangeExtension
, the period is not removed.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)); } }file. file
We used the Path.ChangeExtension
method. This method receives 2 parameters: the path string
you want to change, and the new extension including the leading period.