Path.Combine()盘符后不添加目录分隔 [英] Path.Combine() does not add directory separator after drive letter

查看:285
本文介绍了Path.Combine()盘符后不添加目录分隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了 Path.Combine 方法不正确?
我得到这个结果与 Path.Combine(字符串[])

Am I using the Path.Combine Method Incorrectly?
I Get This Result With Path.Combine(string[]):

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

和这是不太理想的code期望的结果:一个是)由注释掉code产生的结果是:

And This is the desired Result of the less desirable code:the one that is the result generated by the commented out code):

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

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

Note the missing \\ after the drive letter in the first path.

旧的方法(手动添加反斜杠,注释掉)效果很好,但我pretty的肯定,它不会在Linux或别的什么工作,如果编译单。

The old method (manually adding backslashes, commented out) works well, but I'm pretty sure that it wouldn't work under Linux or something else if compiled with mono.

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的目录,而不是项目本身或者它的版本。

Basically, I want the end Result to be the TestProject Directory, not the project itself or its version.

推荐答案

这是在的文档

如果路径1 不可以的驱动器引用(即C:或D:),并执行结尾加上一个有效的分隔符[..], DirectorySeparatorChar 被添加到路径1 前串联。

If path1 is not a drive reference (that is, "C:" or "D:") and does not end with a valid separator character [..], DirectorySeparatorChar is appended to path1 before concatenation.

所以,你的第一条路径,这是驱动器号,并没有得到一个目录分隔符追加。例如,你可以解决这个问题分裂后,通过附加分隔符 TempSave [0] ,但是这会导致问题的Linux像你说的。

So your first path, which is the drive letter, does not get a directory separator appended. You can for example fix this after splitting, by appending the separator to TempSave[0], but that'll cause issues with Linux like you said.

您也可以解决您最实际的问题不同,请参阅如何我找到父目录在C#,或只是追加 .. \ .. \ 像@丹建议,因此您可以跳过分裂:

You can also solve your actual problem differently, see How do I find the parent directory in C#?, or just append ..\..\ like @Dan suggests so you can skip the splitting:

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

这篇关于Path.Combine()盘符后不添加目录分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆