开发者

Why won't this Path.Combine work? [duplicate]

This question already has answers here: Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar? 开发者_运维百科 (16 answers) Closed 9 years ago.

I have the following command:

string reportedContentFolderPath =
Path.Combine(contentFolder.FullName.ToString(), @"\ReportedContent\");

When I look in the debugger I can see the following:

contentFolder.FullName = "E:\\"

However

reportedContentFolderPath = "\\ReportedContent\\"

Why is the Path.Combine chopping off the E:\?


You have a leading slash on @"\ReportedContent\". You don't want that (or the trailing one, I suspect) - try just:

string reportedContentFolderPath =
    Path.Combine(contentFolder.FullName.ToString(), "ReportedContent");

From the documentation:

If path2 does not include a root (for example, if path2 does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If path2 includes a root, path2 is returned.

In your case, path2 did contain a root, so it was returned without looking at path1.


It is explained in the method documentation:

If path2 does not include a root (for example, if path2 does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If path2 includes a root, path2 is returned.

I recommend you read it all to understand how all the possible combinations work out: Path.Combine Method


Path.Combine will return the second argument if it begins with a separation character (\).


I'd bet that by specifying the slash as prefix in the second string, the Combine method assumes the current drive. Try to remove the slash.


From MSDN (emphasis mine):

public static string Combine(string path1, string path2)

[...]

Return Value

Type: System.String The combined paths. If one of the specified paths is a zero-length string, this method returns the other path. If path2 contains an absolute path, this method returns path2.

@"\ReportedContent\" is an absolute path because it begins with a backslash.


It looks like Path.Combine thinks the two slashes E:\\ refers to a UNC path, and a UNC path should not be prefixed with a drive letter. Change the contentFolder to E:\ and it should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜