'C# Uri Combine Different Kinds of BaseURL

Let's say I have 3 different kinds of base url. It can be:

  1. https://www.somewebsite.com/ OR https://www.somewebsite.com/doc/
  2. C:\Files\Docs
  3. https://www.somewebsite.com/doc?name=

I want to combine the base url with a constant part, in the form of file.extension (photo.jpg, doc.pdf...)

I'm using C#'s Uri to do this combine operation:

string baseUrl1 = "https://www.somewebsite.com/";
string baseUrl2 = "C:\Files\Docs";
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());

I'm getting:

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)

In the third case, how do I maintain the URL queries?



Solution 1:[1]

Isn't it easier to just concatenate the strings together? And create the new URL from it. So it would be:

string baseUrl1 = "https://www.somewebsite.com/";
string baseUrl2 = "C:\Files\Docs";
string baseUrl3 = "https://www.somewebsite.com/doc?name=";

string fileName = "doc.pdf";

Uri myUri = new Uri(baseUrl1 + fileName);
Console.WriteLine(myUri.ToString());

If you want to add an extra check if the URI end with or without a / you could add something like:

(baseUrl1.Substring(str.Length-1) == "/") ? "" : "/"

So it could look like:

Uri myUri = new Uri(baseUrl1 + (baseUrl1.Substring(baseUrl1.Length-1) == "/") ? "" : "/" + fileName);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1