Site icon Ryadel

Uri.Combine: how to combine URL-type strings in ASP.NET C#

Classe ASP.NET C# per il controllo e il calcolo formale del Codice Fiscale

The Path.Combine method, available in all ASP.NET programming languages, is a great way to combine multiple strings into a valid File System path. Unfortunately, there is no Uri.Combine method that could be used do achieve the same results with System.Uri objects or URL-type strings.

Since I needed a way to do that, I've just put up some helper methods that can be used to fill that gap: in this post I'm going to share them, so that they can be used to other ASP.NET developers who are looking for a way to combine/append one or more URL-type strings (folders, query strings, and so on) to a Uri object or a URL-type string and have them separated with the appropriate slash ( / ) chars.

StringExtensions

Let's start with a simple StringExtension that can be used whenever we have to deal with URL-type strings:

This will concatenate the base string and all the segments properly, ensuring that we'll have only one slash between them.

UriExtensions

Since we'll most likely have to deal with Uri objects rather than URL-type strings, here are a couple more extension methods that can be used to add the same functionality to the System.Uri ASP.NET class:

As we can see, the first extension method will return a Uri object and internally calls the second one, which in turn calls the previous StringExtension method that returns a string. The whole point of having all three of them available is that those that deals with strings are slightly more efficient: therefore, we'll be able to use them whenever we don't need to return a Uri object.

Append or Combine?

I've purposely called all the above methods using the "Append" term instead of using "Combine" because it seems more appropriate to me: if you prefer to use the same naming convention used  by the .NET staff for the Path.Combine methods, feel free to rename them accordingly.

Alternatively, you can also define some wrapper methods so that you'll be able to call them in multiple ways:

Definitely not as DRY as you could possibly do, yet it could be useful in some edge-case scenarios.

Conclusion

That's it, at least for now: I hope that those helper methods will be useful to other ASP.NET developers who are looking for a way to combine/append one or more URL-type strings (folders, query strings, and so on) to a Uri object or a URL-type string.

Exit mobile version