System.IO.Path.GetPathRoot Method

Gets the root directory information of the specified path.

Syntax

public static string GetPathRoot (string path)

Parameters

path
The path from which to obtain root directory information.

Returns

The root directory of path, such as "C:\", or null if path is null, or an empty string if path does not contain root directory information.

Exceptions

TypeReason
ArgumentException path contains one or more implementation-specific invalid characters or is equal to string.Empty .

Remarks

This method does not verify that the path or file name exists.

Possible patterns for the string returned by this method are as follows:

  • An empty string (path specified a relative path on the current drive or volume).

  • "/" (path specified an absolute path on the current drive).

  • "X:" (path specified a relative path on a drive, where X represents a drive or volume letter).

  • "X:/" (path specified an absolute path on a given drive).

  • "\\ComputerName\SharedFolder" (a UNC path).

The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".

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

Example

The following example demonstrates the Path.GetPathRoot(string) method.

C# Example

using System;
using System.IO;
class GetPathRootTest 
{
  public static void Main() {
    string [] paths = {                                

@"\ecmatest\examples\pathtests.txt",
      "pathtests.xyzzy",
      @"\",
      @"C:\",                                  

@"\\myserver\myshare\foo\bar\baz.txt"
    };
    foreach (string pathString in paths) {
      string s = Path.GetPathRoot(pathString);
      Console.WriteLine("Path: {0} Path root is {1}",pathString, s== null? "null": s);
    }
  }
}

The output is

Path: \ecmatest\examples\pathtests.txt Path root is \
Path: pathtests.xyzzy Path root is
Path: \ Path root is \
Path: C:\ Path root is C:\
Path: \\myserver\myshare\foo\bar\baz.txt Path root is \\myserver\myshare

Requirements

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