如何有效地使用 Path.Combine 在字符串中以反斜杠开头?

Raj*_*ian 1 c# path

我正在使用 C# Path.Combine 方法来组合路径,如下所示

string str1 = "C:";                   // This value can be read from configuration
string str2 = "\Dataaccess\bin";      // This value can be read from configuration
string combinedPath = Path.Combine(str1,str2);
Run Code Online (Sandbox Code Playgroud)

我的期望是组合路径应该返回“C:\ Dataaccess \ bin”但它返回\ Dataaccess \ bin

如果我将 str1 值更改为“C:”,如下所示,

string str1 = "C:\";                   // This value can be read from configuration
string str2 = "\Dataaccess\bin";      // This value can be read from configuration
string combinedPath = Path.Combine(str1,str2);
Run Code Online (Sandbox Code Playgroud)

然后它也返回 \Dataaccess\bin

如果我将 str1 值更改为“C:”,然后将 str2 值更改为“Dataaccess\bin”,如下所示,

string str1 = "C:\";                   // This value can be read from configuration
string str2 = "Dataaccess\bin";      // This value can be read from configuration
string combinedPath = Path.Combine(str1,str2);
Run Code Online (Sandbox Code Playgroud)

然后只有它返回正确的值“C:\Dataaccess\bin”

如何使用输入“C:”和“\Dataaccess\bin”获得预期结果“C:\Dataaccess\bin”,因为这两个值是从无法更改的配置文件中检索的。

Tim*_*ter 5

我认为最简单的方法是删除\开头的str2

str2 = str2.TrimStart('\\');
string combinedPath = Path.Combine(str1, str2);
Run Code Online (Sandbox Code Playgroud)

至于为什么它会这样:它记录在Path.Combine

如果后续路径之一是绝对路径,则组合操作将从该绝对路径开始重置,并丢弃所有先前的组合路径

第二个字符串str2是 UNC 路径,因此是绝对路径,因为它是root

.NET 来源:

private static string CombineInternal(string first, string second)
{
    if (string.IsNullOrEmpty(first))
        return second;

    if (string.IsNullOrEmpty(second))
        return first;

    if (IsPathRooted(second.AsSpan()))
        return second;

    return JoinInternal(first.AsSpan(), second.AsSpan());
}
Run Code Online (Sandbox Code Playgroud)