0

与えられた相対パス文字列:

"SomeFolder\\Container\\file.txt"

最上位の親またはルートフォルダを特定したい"SomeFolder"

Path.GetPathRoot("SomeFolder\\Container\\file.txt"); // returns empty

「stringvoodoo」を避けて、異なるディレクトリセパレータを備えたシステムに移植できるようにしたいと思います。

私が見落としている明らかな方法はありますか?

4

2 に答える 2

0

Path.GetPathRootメソッドから:

「C:\」などのパスのルートディレクトリを返します。パスがnullの場合はnullを返し、パスにルートディレクトリ情報が含まれていない場合は空の文字列を返します。

あなたの道は根付いていません。そのため、結果として空の文字列が取得されます。を呼び出す前に、まずパスがルート化されているかどうかを確認する必要がありますGetPathRoot()

var somePath = "SomeFolder\\Container\\file.txt";

String root;
if (Path.IsPathRooted(somePath))
    root = Path.GetPathRoot(somePath);
else
    root = somePath.Split(Path.DirectorySeparatorChar).First();
于 2013-03-07T00:45:51.543 に答える
0

@Willは、Uri他のいくつかのパス操作に使用したクラスの使用を提案しました。

私はこれを次の方法で解決しました:

/// <summary>
/// Returns the path root if absolute, or the topmost folder if relative.
/// The original path is returned if no containers exist.
/// </summary>
public static string GetTopmostFolder(string path)
{
    if (path.StartsWith(Path.DirectorySeparatorChar.ToString()))
        path = path.Substring(1);

    Uri inputPath;

    if (Uri.TryCreate(path, UriKind.Absolute, out inputPath))
        return Path.GetPathRoot(path);

    if (Uri.TryCreate(path, UriKind.Relative, out inputPath))
        return path.Split(Path.DirectorySeparatorChar)[0];

    return path;
}

編集:

先頭のディレクトリ区切り文字を削除するように変更されました。入力文字列が含まれているとは思いませんが、念のために計画しておくとよいでしょう。

于 2013-03-07T00:57:49.043 に答える