Path.Combine()在驱动器号后面不添加目录分隔符

Sam*_*uel 10 .net c# path

我使用的Path.Combine方法不正确吗?
我得到这个结果Path.Combine(string[]):

C:Users\\Admin\\AppData\\Roaming\\TestProject\\Connections.xml
Run Code Online (Sandbox Code Playgroud)

这是不太理想的代码的期望结果:由注释掉的代码生成的结果:

C:\\Users\\Admin\\AppData\\Roaming\\TestProject\\Connections.xml
Run Code Online (Sandbox Code Playgroud)

请注意\\第一个路径中的驱动器号后面缺少的.

旧的方法(手动添加反斜杠,注释掉)运行良好,但我很确定如果用mono编译,它在Linux或其他东西下不起作用.

string[] TempSave = Application.UserAppDataPath.Split(Path.DirectorySeparatorChar);
string[] DesiredPath = new string[TempSave.Length - 2];
for (int i = 0; i < TempSave.Length - 2; i++)
{
    //SaveLocation += TempSave[i] + "\\";//This Works
    DesiredPath[i] = TempSave[i];
}
SaveLocation = Path.Combine(DesiredPath);//This Doesn't Work.    
ConnectionsFs = new FileStream(Path.Combine(SaveLocation,FileName)/*SaveLocation+FileName*/, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
Run Code Online (Sandbox Code Playgroud)

基本上,我希望最终结果是TestProject目录,而不是项目本身或其版本.

Cod*_*ter 6

它在文档中:

如果path1驱动的参考(即,"C:"或"d")和不具有有效分隔字符结尾[..],DirectorySeparatorChar被追加到path1级联之前.

因此,您的第一个路径(即驱动器号)不会附加目录分隔符.例如,您可以通过附加分隔符来解决此TempSave[0]问题,但这会导致Linux问题,就像您说的那样.

您也可以用不同的方式解决实际问题,请参阅如何在C#中找到父目录?,或者..\..\像@Dan建议的那样追加,这样你就可以跳过拆分:

string desiredPath = Path.Combine(Application.UserAppDataPath, @"..\..\");
Run Code Online (Sandbox Code Playgroud)