4

我遇到了 Uri 构造函数的问题。结果因基本路径是否以斜线结尾而异。

var baseWithSlash = new Uri("c:\\Temp\\");
var baseNoSlash = new Uri("c:\\Temp");

var relative = "MyApp";

var pathWithSlash = new Uri(baseWithSlash, relative);  // file:///c:/Temp/MyApp
var pathNoSlash = new Uri(baseNoSlash, relative);      // file:///c:/MyApp

第一个结果是我期望的结果,即使基本路径中没有斜杠。

我的主要问题是基本路径来自用户输入。

即使用户指定没有斜杠的路径,获得正确结果的最佳方法是什么?

4

2 回答 2

9

This is to be expected IMO. After all, consider the URI for "hello.jpg" relative to

 http://foo.com/site/index.html

It's

 http://foo.com/site/hello.jpg

right?

Now if you know that your user is entering a URI representing a directory, you can make sure that the string has a slash on the end. The problem comes if you don't know whether they're entering a directory name or not. Will just adding a slash if there isn't one already work for you?

string baseUri = new Uri(userUri + userUri.EndsWith("\\") ? "" : "\\");

That's assuming (based on your example) that they'll be using backslashes. Depending on your exact circumstance, you may need to handle forward slashes as well.

于 2009-10-13T06:10:53.503 回答
0

确保第一部分有一个尾部斜杠(即:检查它)。

于 2009-10-13T06:06:20.233 回答