System.IO.Path.GetFileName Method

Returns the file name and extension of the specified path string.

Syntax

public static string GetFileName (string path)

Parameters

path
The path string from which to obtain the file name and extension.

Returns

The characters after the last directory character in path. If the last character of path is a directory or volume separator character, this method returns string.Empty. If path is null, this method returns null.

Exceptions

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

Remarks

The returned value is null if the file path is null.

The separator characters used to determine the start of the file name are Path.DirectorySeparatorChar and Path.AltDirectorySeparatorChar.

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

Example

The following example demonstrates the behavior of the Path.GetFileName(string) method on a Windows system.

C# Example

using System;
using System.IO;
class FileNameTest {
 public static void Main() {
   string [] paths = {"pathtests.txt",
     @"\ecmatest\examples\pathtests.txt",
     "c:pathtests.txt",
     @"\ecmatest\examples\",
     ""
   };
   foreach (string p in paths) {
     Console.WriteLine("Path: {0} filename = {1}",p, Path.GetFileName(p));
   }
 }
}
      

The output is

Path: pathtests.txt filename = pathtests.txt
Path: \ecmatest\examples\pathtests.txt filename = pathtests.txt
Path: c:pathtests.txt filename = pathtests.txt
Path: \ecmatest\examples\ filename =
Path: filename =

Requirements

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