【发布时间】:2013-11-23 09:52:29
【问题描述】:
根据官方文档关于Path.Combine方法:https://msdn.microsoft.com/en-us/library/fyy7a5kt(v=vs.110).aspx
备注
如果 path1 不是驱动器引用(即“C:”或“D:”)并且不以 DirectorySeparatorChar、AltDirectorySeparatorChar 或 VolumeSeparatorChar 中定义的有效分隔符结尾,则 DirectorySeparatorChar 在连接之前附加到 path1 .
这意味着它不会在驱动器号后添加\ ,所以这段代码:
var path1 = @"c:";
var path2 = @"file.txt";
Path.Combine(path1, path2);
将生成C:file.txt,它不会强制指向放在c: 中的文件file.txt。
这背后的原因是什么?
【问题讨论】:
-
也许是因为它是小写的? msdn.microsoft.com/en-us/library/… 我会用
var path1 = "c:\\"; -
我刚刚做了一个测试,可以确认
C:\temp>start c:live_14_09_2017.txt工作(在我的系统上)。我相信c:file.txt可能意味着c 盘当前目录中的file.txt。因此,在我的情况下,该文件位于临时目录中(即我在 c 上的当前目录),因此它可以工作。遗憾的是,如果我在 d 驱动器上,我没有任何其他驱动器号可用于测试这是否确实有效,但我认为假设path2是 c 驱动器上的相对路径可能是一个合理的假设。 -
C:file.txt在 Windows 中绝对是有效路径,就像在 DOS 中一样。 -
文档 (msdn.microsoft.com/en-us/library/windows/desktop/…) 证实了@chris 的观察结果:
If a file name begins with only a disk designator but not the backslash after the colon, it is interpreted as a relative path to the current directory on the drive with the specified letter. Note that the current directory may or may not be the root directory depending on what it was set to during the most recent "change directory" operation on that disk -
C:XXX 是 XXX 相对于 C: 上当前工作目录的路径
标签: c#