假设我有3种不同的基本url。它可以是:
- https://www.somewebsite.com/或https://www.somewebsite.com/doc/
- C: \文件\文档
- https://www.somewebsite.com/doc?name=
我想将基本url与一个常量部分结合起来,形式为file.extension
(photo.jpg,doc.pdf…(
我使用C#的Uri来执行这个合并操作:
string baseUrl1 = "https://www.somewebsite.com/";
string baseUrl2 = "C:FilesDocs";
string baseUrl3 = "https://www.somewebsite.com/doc?name=";
string fileName = "doc.pdf";
Uri baseUri = new Uri(baseUrl1);
Uri myUri = new Uri(baseUri, fileName);
Console.WriteLine(myUri.ToString());
我得到:
1: https://www.somewebsite.com/doc.pdf
2: file:///C:/Files/Docs/1cy1ipsf.pdf
3: https://www.somewebsite.com/doc.pdf (I expected: https://www.somewebsite.com/doc?name=doc.pdf)
在第三种情况下,如何维护URL查询?
将字符串连接在一起不是更容易吗?并从中创建新的URL。因此它将是:
string baseUrl1 = "https://www.somewebsite.com/";
string baseUrl2 = "C:FilesDocs";
string baseUrl3 = "https://www.somewebsite.com/doc?name=";
string fileName = "doc.pdf";
Uri myUri = new Uri(baseUrl1 + fileName);
Console.WriteLine(myUri.ToString());
如果你想添加一个额外的检查URI是否以/结尾,你可以添加这样的内容:
(baseUrl1.Substring(str.Length-1) == "/") ? "" : "/"
所以它可能看起来像:
Uri myUri = new Uri(baseUrl1 + (baseUrl1.Substring(baseUrl1.Length-1) == "/") ? "" : "/" + fileName);