System.IO.Path.GetExtension Method

Returns the extension of the specified path string.

Syntax

public static string GetExtension (string path)

Parameters

path
The path string from which to get the extension.

Returns

The extension of the specified path (including the period "."), or null, or string.Empty. If path is null, Path.GetExtension(string) returns null. If path does not have extension information, Path.GetExtension(string) returns string.Empty.

Exceptions

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

Remarks

The extension of path is obtained by searching path for a period (.), starting with the last character in path and continuing toward the start of path. If a period is found before a Path.DirectorySeparatorChar or Path.AltDirectorySeparatorChar character, the returned string contains the period and the characters after it; otherwise, string.Empty is returned.

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

Example

The following example demonstrates using the Path.GetExtension(string) method on a Windows system.

C# Example

using System;
using System.IO;
class GetDirectoryTest {
 public static void Main(){
   string [] paths = {
     @"\ecmatest\examples\pathtests.txt",
     @"\ecmatest\examples\",
     "pathtests.xyzzy",
     "pathtests.xyzzy.txt",
     @"\",
     ""
   };
   foreach (string pathString in paths){
     string s = Path.GetExtension (pathString);
     if (s == String.Empty) s= "(empty string)";
     if (s == null) s= "null";
     Console.WriteLine("{0} is the extension of {1}", s, pathString);
   }
 }
}

The output is

.txt is the extension of \ecmatest\examples\pathtests.txt
(empty string) is the extension of \ecmatest\examples\
.xyzzy is the extension of pathtests.xyzzy
.txt is the extension of pathtests.xyzzy.txt
(empty string) is the extension of \
(empty string) is the extension of

Requirements

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