【发布时间】:2016-05-16 23:21:52
【问题描述】:
我注意到当我使用 Path.GetFullPath(Path.Combine(@"c:\folder\","\subfolder\file.txt")) 时,它会返回路径 c:\subfolder\file.txt,而不是预期的组合路径 c:\folder\subfolder\file.txt。这些方法似乎没有处理第二个组合输入上的“\”。有没有人遇到过这种情况并找到了合并路径的更好解决方案?
var test1 = Path.GetFullPath(Path.Combine(@"C:\users\dev\desktop\testfiles\", @".\test1.txt"));
var test2 = Path.GetFullPath(Path.Combine(@"C:\users\dev\desktop\testfiles\", @"\test2.txt"));//
var test3 = Path.GetFullPath(Path.Combine(@"C: \users\dev\desktop\testfiles\", @"test3.txt"));
var test4 = Path.GetFullPath(Path.Combine(@"C:\users\dev\desktop\testfiles\",@".\XXX\test4.txt"));
var test5 = Path.GetFullPath(Path.Combine(@"C:\users\dev\desktop\testfiles\", @"\XXX\test5.txt"));//
var test6 = Path.GetFullPath(Path.Combine(@"C:\users\dev\desktop\testfiles\", @"XXX\test6.txt"));
var test7 = Path.GetFullPath(Path.Combine(@"C:\users\dev\desktop\testfiles\", @"\somefile\that\doesnt\exist.txt"));//
结果
test1 is "C:\users\dev\desktop\testfiles\test1.txt"
test2 is wrong "\test2.txt"
test3 is "C: \users\dev\desktop\testfiles\test3.txt"
test4 is "C:\users\dev\desktop\testfiles\XXX\test4.txt"
test5 is wrong "c:\XXX\test5.txt"
test6 is "C:\users\dev\desktop\testfiles\XXX\test6.txt"
test7 is wrong "c:\somefile\that\doesnt\exist.txt"
基本上我正在做的是将源路径与文本文件中的单个文件路径结合起来,以便我可以将这些文件复制到目标,并且我想维护子文件夹层次结构。
例如文件列表相同但想要引用特定源文件夹版本的常见场景。
source path + individual file path
\\myserver\project\1.x + \dll\important.dll
应该以同样的方式复制到目的地
c:\myproject\ + \dll\important.dll
所以会有变量;源、目标、文件[数组或列表]
我目前的前进方式是使用 String.TRIM() 方法删除特殊字符。 \ / 在将路径与 Path.Combine、Path.GetFullPath 组合之前。但我想也许有人已经意识到类似情况的更好方法。
在目的地创建子文件夹也很痛苦,基本上我使用 String.LastIndexOf(@'\') 将文件名与文件夹名分开。这似乎也有点粗略,但更好的方法超出了我的经验。
类似的问题: Path.Combine absolute with relative path strings
感谢反馈,我现在知道 \file.txt 被视为完全限定(绝对)路径,这就是 combine 方法以这种方式工作的原因。
如果文件名不以下列之一开头,则该文件名相对于当前目录:
A UNC name of any format, which always start with two backslash characters ("\\"). For more information, see the next section.
A disk designator with a backslash, for example "C:\" or "d:\".
A single backslash, for example, "\directory" or "\file.txt". This is also referred to as an absolute path.
【问题讨论】:
-
“组合”方法第二部分中的第一个反斜杠似乎使您的路径返回到“c:\”作为基本路径。也许您可以过滤掉第一个“\”?
标签: c#