获取相对路径的第一个目录名

本文关键字:第一个 相对 路径 获取 | 更新日期: 2023-09-27 18:12:44

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

例如:

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

获取相对路径的第一个目录名

适用于正斜杠和反斜杠

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

似乎您可以在字符串上使用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"

最可靠的解决方案是使用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;
    }
}

根据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;
}

这将给顶层文件夹

根据你提出的问题,以下应该是有效的:

    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作为所需-对于/情况相同

这里是另一个例子,如果你的路径是以下格式:

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

应该没问题

string str = "foo'bar'abc.txt";
string str2 = "bar/foo/foobar";
str.Replace("/", "''").Split('''').First(); // foo
str2.Replace("/", "''").Split('''').First(); // bar

下面是我的例子,没有内存占用(不在内存中创建新字符串):

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);