GetPathRootメソッドを使うことでパスからルートディレクトリを取得することができます。 ドライブ名を含むパスの場合は、ドライブ名も含めたルートディレクトリが返されます。 例えば、パスE:\dir
の場合はEドライブのルートディレクトリE:\
が返されます。 カレントドライブからの相対パス\dir
では、ドライブ名の指定がないルートディレクトリ\
のみが返されます。 (カレントディレクトリからの)相対パスなど、ルートディレクトリからのパスでない場合は、空の文字列が返されます。
また、パスがルートディレクトリから始まっているかどうか(ルートディレクトリからのパスであるか)を調べるにはIsPathRootedメソッドを使うことができます。 ルートディレクトリとして判断される基準はGetPathRootメソッドと同様です。
GetPathRoot・IsPathRootedメソッドではあくまでパス形式としての検証のみが行われるため、実在しないルートディレクトリの場合でも例外は発生しません。
Path.GetPathRoot/IsPathRootedメソッドでルートディレクトリを抽出する/ルートディレクトリからのパスか調べる
using System;
using System.IO;
class Sample {
static void Main()
{
foreach (var path in new[] {
@"E:\dir\subdir\file.txt", // 絶対パス (Windows形式)
@"/dir/subdir/file.txt", // 絶対パス (UNIX形式)
@"\\127.0.0.1\e$\dir\file.txt", // UNCパス
@"\dir\subdir\file.txt", // 相対パス (Windows形式・カレントドライブからの相対パス)
@".\dir\subdir\file.txt", // 相対パス (Windows形式・カレントディレクトリからの相対パス)
@"./dir/subdir/file.txt", // 相対パス (UNIX形式)
@"file.txt", // ファイル名のみのパス
}) {
Console.WriteLine("path = {0}", path);
Console.WriteLine("root = {0}", Path.GetPathRoot(path)); // パスからルートディレクトリを抽出する
Console.WriteLine("rooted? {0}", Path.IsPathRooted(path)); // パスがルートディレクトリから始まっているかどうか調べる
Console.WriteLine();
}
}
}
実行結果
path = E:\dir\subdir\file.txt root = E:\ rooted? True path = /dir/subdir/file.txt root = \ rooted? True path = \\127.0.0.1\e$\dir\file.txt root = \\127.0.0.1\e$ rooted? True path = \dir\subdir\file.txt root = \ rooted? True path = .\dir\subdir\file.txt root = rooted? False path = ./dir/subdir/file.txt root = rooted? False path = file.txt root = rooted? False
実行結果
path = E:\dir\subdir\file.txt root = rooted? False path = /dir/subdir/file.txt root = / rooted? True path = \\127.0.0.1\e$\dir\file.txt root = rooted? False path = \dir\subdir\file.txt root = rooted? False path = .\dir\subdir\file.txt root = rooted? False path = ./dir/subdir/file.txt root = rooted? False path = file.txt root = rooted? False
パスがUNCパスなどの完全修飾になっているかどうかを調べるにはPath.IsPathFullyQualifiedメソッドを使うことができます。