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

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

 C:Users\\Admin\\AppData\\Roaming\\TestProject\\Connections.xml 

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

 C:\\Users\\Admin\\AppData\\Roaming\\TestProject\\Connections.xml 

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

旧方法(手动添加反斜杠,注释掉)效果很好,但我很确定如果使用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); 

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

它在文档中 :

如果path1 不是驱动器引用(即“C:”或“D:”)并且不以有效的分隔符[…]结束,则在连接之前将DirectorySeparatorChar附加到path1

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

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

 string desiredPath = Path.Combine(Application.UserAppDataPath, @"..\..\");