gpt4 book ai didi

c# - 具有驱动器号的 Path.Combine() 行为

转载 作者:可可西里 更新时间:2023-11-01 09:11:52 26 4
gpt4 key购买 nike

根据有关Path.Combine 方法的官方文档:https://msdn.microsoft.com/en-us/library/fyy7a5kt(v=vs.110).aspx

Remarks

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

这意味着它不会在盘符后面加上\,所以这段代码:

var path1 = @"c:";
var path2 = @"file.txt";
Path.Combine(path1, path2);

将生成 C:file.txt,它不会强制指向放置在 c: 中的文件 file.txt

这背后的原因是什么?

最佳答案

Path.Combine 以这种方式工作,因为 c:file.txt 实际上是一个有效路径。

根据 Microsoft documentation on NTFS paths :

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:file.txt会搜索C盘当前目录下的文件,而c:\file.txt会搜索驱动器根文件夹中的文件(忽略当前目录)。

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

关于c# - 具有驱动器号的 Path.Combine() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19909008/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com