C#:获取相对路径的第一个目录名称

时间:2011-10-27 03:33:45

标签: c# string path .net

如何在相对路径中获取第一个目录名,假设它们可以是不同的接受目录分隔符?

例如:

foo\bar\abc.txt -> foo
bar/foo/foobar -> bar

8 个答案:

答案 0 :(得分:10)

好像你可以在字符串上使用string.Split()方法,然后抓住第一个元素 示例(未经测试):

string str = "foo\bar\abc.txt";
string str2 = "bar/foo/foobar";


string[] items = str.split(new char[] {'/', '\'}, StringSplitOptions.RemoveEmptyEntries);

Console.WriteLine(items[0]); // prints "foo"

items = str2.split(new char[] {'/', '\'}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(items[0]); // prints "bar"

答案 1 :(得分:8)

适用于正斜杠和反斜杠

static string GetRootFolder(string path)
{
    while (true)
    {
        string temp = Path.GetDirectoryName(path);
        if (String.IsNullOrEmpty(temp))
            break;
        path = temp;
    }
    return path;
}

答案 2 :(得分:5)

最强大的解决方案是使用DirectoryInfoFileInfo。在基于Windows NT的系统上,它应该接受分隔符的正斜杠或反斜杠。

using System;
using System.IO;

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine(GetTopRelativeFolderName(@"foo\bar\abc.txt")); // prints 'foo'
        Console.WriteLine(GetTopRelativeFolderName("bar/foo/foobar")); // prints 'bar'
        Console.WriteLine(GetTopRelativeFolderName("C:/full/rooted/path")); // ** throws
    }

    private static string GetTopRelativeFolderName(string relativePath)
    {
        if (Path.IsPathRooted(relativePath))
        {
            throw new ArgumentException("Path is not relative.", "relativePath");
        }

        FileInfo fileInfo = new FileInfo(relativePath);
        DirectoryInfo workingDirectoryInfo = new DirectoryInfo(".");
        string topRelativeFolderName = string.Empty;
        DirectoryInfo current = fileInfo.Directory;
        bool found = false;
        while (!found)
        {
            if (current.FullName == workingDirectoryInfo.FullName)
            {
                found = true;
            }
            else
            {
                topRelativeFolderName = current.Name;
                current = current.Parent;
            }
        }

        return topRelativeFolderName;
    }
}

答案 3 :(得分:2)

基于Hasan Khan ...

提供的答案
private static string GetRootFolder(string path)
{
    var root = Path.GetPathRoot(path);
    while (true)
    {
        var temp = Path.GetDirectoryName(path);
        if (temp != null && temp.Equals(root))
            break;
        path = temp;
    }
    return path;
}

这将提供顶级文件夹

答案 4 :(得分:1)

根据您提出的问题,以下内容应该有效:

    public string GetTopLevelDir(string filePath)
    {
        string temp = Path.GetDirectoryName(filePath);
        if(temp.Contains("\\"))
        {
            temp = temp.Substring(0, temp.IndexOf("\\"));
        }
        else if (temp.Contains("//"))
        {
            temp = temp.Substring(0, temp.IndexOf("\\"));
        }
        return temp;
    }

当传递foo\bar\abc.txt时,它将foo按需要 - 与/ case

相同

答案 5 :(得分:0)

以下是另一个例子,如果您的路径符合以下格式:

string path = "c:\foo\bar\abc.txt"; // or c:/foo/bar/abc.txt
string root = Path.GetPathRoot(path); // root == c:\

答案 6 :(得分:0)

这应该很好

string str = "foo\bar\abc.txt";
string str2 = "bar/foo/foobar";

str.Replace("/", "\\").Split('\\').First(); // foo
str2.Replace("/", "\\").Split('\\').First(); // bar

答案 7 :(得分:0)

这里是我的示例,没有占用内存(无需在内存中创建新字符串):

var slashIndex = relativePath.IndexOf('/');
var backslashIndex = relativePath.IndexOf('\\');
var firstSlashIndex = (slashIndex > 0) ? (slashIndex < backslashIndex ? slashIndex : (backslashIndex == -1) ? slashIndex : backslashIndex) : backslashIndex;
var rootDirectory = relativePath.Substring(0, firstSlashIndex);