【问题标题】:Path.Combine() behaviour with drive lettersPath.Combine() 行为与驱动器号
【发布时间】: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#


【解决方案1】:

Path.Combine 之所以如此工作,是因为c:file.txt 实际上是一个有效路径。

根据Microsoft documentation on NTFS paths

如果文件名仅以磁盘指示符开头,而冒号后没有反斜杠,则将其解释为具有指定字母的驱动器上当前目录的相对路径。请注意,当前目录可能是根目录,也可能不是根目录,具体取决于该磁盘上最近一次“更改目录”操作期间设置的内容。

简单来说c:file.txt会搜索C盘当前目录下的文件,c:\file.txt会搜索驱动器根目录下的文件(忽略当前目录)。

由于Path.Combine 无法知道您期望的行为是什么,因此它无法自动添加反斜杠。

【讨论】:

【解决方案2】:

documentation:

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

所以你的第一个路径,即驱动器号,没有附加目录分隔符。

【讨论】:

    【解决方案3】:

    c:c:\ 的路径不相同。

    • c: 是驱动器规范,操作系统会在需要时附加当前文件夹。

    • c:\ 是驱动器的根文件夹,如c: + \

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多