[C#] Changing File Extensions (Path.ChangeExtension)

When renaming files, especially when you only want to change the extension (e.g., .jpeg -> .jpg), performing manual string manipulation often leads to errors in determining the position of the dot.

Using the Path.ChangeExtension method allows you to safely obtain a new path string with only the extension part rewritten.

Important: This method only creates a “new path string”; it does not change the actual file name. To change the file name, you must call File.Move afterwards.

目次

Table of Contents

  • Implementation Sample: Fixing Incorrect Extensions
  • Sample Code
  • Execution Result
  • Explanation and Technical Points
    1. Behavior of Path.ChangeExtension
    2. Combination with File.Move
    3. Using Temporary Files

Implementation Sample: Fixing Incorrect Extensions

In the following code, I perform a process to change a file that has an incorrect .text extension to the correct .txt extension.

Sample Code

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        // 1. Preparation: Create a test file (extension is .text)
        string originalPath = "memo.text";
        if (!File.Exists(originalPath))
        {
            File.WriteAllText(originalPath, "This is a test.");
        }

        Console.WriteLine($"Before Change: {originalPath}");

        // 2. Create a path string with the new extension
        // 1st Argument: Original path
        // 2nd Argument: New extension (Okay with or without the dot)
        // *The file name has not changed yet at this point!
        string newPath = Path.ChangeExtension(originalPath, ".txt");

        Console.WriteLine($"After Change (Planned): {newPath}");

        // 3. Actually change the file name (Move operation)
        if (File.Exists(originalPath))
        {
            // It is safer to check if a file with the new name already exists before executing
            if (!File.Exists(newPath))
            {
                File.Move(originalPath, newPath);
                Console.WriteLine("File name change complete.");
            }
            else
            {
                Console.WriteLine("Error: The file name after change already exists.");
            }
        }
    }
}

Execution Result

Before Change: memo.text
After Change (Planned): memo.txt
File name change complete.

Explanation and Technical Points

1. Behavior of Path.ChangeExtension

This method does not access the file system; it performs a pure string replacement.

  • It looks for the extension at the end of the string and replaces it with the specified extension.
  • If you pass null as the second argument, it returns the path with the extension removed (memo).
  • The dot in the second argument is optional (writing "txt" will automatically become .txt).

2. Combination with File.Move

A common mistake for beginners is to think that calling Path.ChangeExtension alone changes the file. You must execute File.Move(oldPath, newPath) to instruct the OS to perform the rename operation.

3. Using Temporary Files

This technique is also often used for transactional processing, such as creating a temporary working file (.tmp) and then changing it to the formal extension (e.g., .csv) once the process is complete.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次