Path.IsPathRooted and Path.GetPathRoot
Path.IsPathRooted method gets a value indicating whether the specified path string contains absolute or relative path information.
string fileName = @"C:\mydir\myfile.ext";
string UncPath = @"\\myPc\mydir\myfile";
string relativePath = @"mydir\sudir\";
bool result;
result = Path.IsPathRooted(fileName);
Console.WriteLine("IsPathRooted('{0}') returns {1}",
fileName, result);
result = Path.IsPathRooted(UncPath);
Console.WriteLine("IsPathRooted('{0}') returns {1}",
UncPath, result);
result = Path.IsPathRooted(relativePath);
Console.WriteLine("IsPathRooted('{0}') returns {1}",
relativePath, result);
This code produces output similar to the following:
IsPathRooted('C:\mydir\myfile.ext') returns True
IsPathRooted('\\myPc\mydir\myfile') returns True
IsPathRooted('mydir\sudir\') returns False
Path.GetPathRoot method returns the root directory information for a path string.
string path = @"\mydir\";
string fileName = "myfile.ext";
string fullPath = @"C:\mydir\myfile.ext";
string pathRoot;
pathRoot = Path.GetPathRoot(path);
Console.WriteLine("GetPathRoot('{0}') returns '{1}'",
path, pathRoot);
pathRoot = Path.GetPathRoot(fileName);
Console.WriteLine("GetPathRoot('{0}') returns '{1}'",
fileName, pathRoot);
pathRoot = Path.GetPathRoot(fullPath);
Console.WriteLine("GetPathRoot('{0}') returns '{1}'",
fullPath, pathRoot);
This code produces output similar to the following:
GetPathRoot('\mydir\') returns '\'
GetPathRoot('myfile.ext') returns ''
GetPathRoot('C:\mydir\myfile.ext') returns 'C:\'