System.IO.Path.ChangeExtension Method

Changes the extension of a path string.

Syntax

public static string ChangeExtension (string path, string extension)

Parameters

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

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.

Exceptions

TypeReason
ArgumentException path contains one or more implementation-specific invalid characters.

Remarks

If neither path nor extension contains a period (.), ChangeExtension adds the period.

The extension parameter can contain multiple periods and any valid path characters, and can be any length. If extension is null, the returned string contains the contents of path with the last period and all characters following it removed.

If extension is an empty string, the returned path string contains the contents of path with any characters following the last period removed.

If path does not have an extension and extension is not null, the returned string contains path followed by extension.

If extension is not null and does not contain a leading period, the period is added.

If path contains a multiple extension separated by multiple periods, the returned string contains the contents of path with the last period and all characters following it replaced by extension. For example, if path is "\Dir1\examples\pathtests.csx.txt" and extension is "cs", the modified path is "\Dir1\examples\pathtests.csx.cs".

It is not possible to verify that the returned results are valid in all scenarios. For example, if path is empty, extension is appended.

For a list of common I/O tasks, see Common I/O Tasks.

Requirements

Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0