Home > Enterprise >  C# Uri Combine Different Kinds of BaseURL
C# Uri Combine Different Kinds of BaseURL

Time:03-24

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?

CodePudding user response:

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);

CodePudding user response:

You can only by Concatenating, but you can try adjusting your code to utilize UriBuilder or Path.Combine (only for files)

https://dotnetcodr.com/2015/04/28/how-to-build-uris-with-the-uribuilder-class-in-c/ https://docs.microsoft.com/en-us/dotnet/api/system.uribuilder?view=net-6.0

https://docs.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=net-6.0

  •  Tags:  
  • c#
  • Related