C# Path ChangeExtension

Description

Path ChangeExtension Changes the extension of a path string.

Syntax

Path.ChangeExtension has the following syntax.


public static string ChangeExtension(
  string path,
  string extension
)

Parameters

Path.ChangeExtension has the following parameters.

  • path - The path information to modify. The path cannot contain any of the characters defined in GetInvalidPathChars.
  • extension - The new extension (with or without a leading period). Specify null to remove an existing extension from path.

Returns

Path.ChangeExtension method returns The modified path information. On Windows-based desktop platforms, if path is null or an empty string (""), the path information is returned unmodified. If extension is null, the returned string contains the specified path with its extension removed. If path has no extension, and extension is not null, the returned path string contains extension appended to the end of path.

Example

The following code example demonstrates a use of the ChangeExtension method.


//from  www  .ja v a2s.c om
using System;
using System.IO;

public class PathSnippets
{

    public static void Main()
    {
        string goodFileName = @"C:\mydir\myfile.com.extension";
        string badFileName = @"C:\mydir\";
        string result;

        result = Path.ChangeExtension(goodFileName, ".old");
        Console.WriteLine("ChangeExtension({0}, '.old') returns '{1}'",goodFileName, result); 

    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.IO »




BinaryReader
BinaryWriter
Directory
DirectoryInfo
DriveInfo
File
FileInfo
FileStream
MemoryStream
Path
StreamReader
StreamWriter
StringReader
StringWriter