简体   繁体   中英

How can I determine the topmost folder (root) of a relative path?

Given the relative path string:

"SomeFolder\\Container\\file.txt"

I want to determine the topmost parent or root folder, "SomeFolder" .

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

I'd prefer to avoid "string voodoo" so that this can be ported to systems with different directory separators.

Is there some obvious method that I am overlooking?

From Path.GetPathRoot Method :

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.

Your path isn't rooted. That's why you're getting the empty string as a result. You should first check if the path is rooted, before you call GetPathRoot() .

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

String root;
if (Path.IsPathRooted(somePath))
    root = Path.GetPathRoot(somePath);
else
    root = somePath.Split(Path.DirectorySeparatorChar).First();

@Will suggested use of the Uri class, which I have used for some other path operations to great effect.

I solved this with the following method:

/// <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;
}

Edit:

Modified to strip off leading directory separators. I don't anticipate having any input strings with them, but it's good to plan just in case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM