To combine multiple Uri in C# and VB.NET you can use the following snippet.

Simple Sample (combining 2 uri)

Sample C#

public string CombineUri(string uri1, string uri2)
	if (uri1.Length == 0){return uri2;}
	if (uri2.Length == 0){return uri1;}
	uri1 = uri1.TrimEnd('/', '\\');
	uri2 = uri2.TrimStart('/', '\\');
	return string.Format("{0}/{1}", uri1, uri2);

Sample VB.NET (autogenerated)

Public Function CombineUri(uri1 As String, uri2 As String) As String
	If uri1.Length = 0 Then
		Return uri2
	End If
	If uri2.Length = 0 Then
		Return uri1
	End If
	uri1 = uri1.TrimEnd("/", "\")
	uri2 = uri2.TrimStart("/", "\")
	Return String.Format("{0}/{1}", uri1, uri2)
End Function

UPDATE 23.06.2015

Combine multiple Uri

Since this snippet is one of our most read snippets of all time, i decided to upgrade this snippet.
This method now uses params string[] as method parameter which allows much more uri strings to be combine at once.

Sample C#

public string CombineUri(params string[] uriParams)
	var retVal = string.Empty;
	foreach (var uriParam in uriParams)
		var tempParam = uriParam.Trim();
		if (!String.IsNullOrEmpty(tempParam))
			tempParam = uriParam.TrimEnd('/', '\\');
			retVal = !String.IsNullOrEmpty(retVal) ? string.Format("{0}/{1}", retVal, tempParam) : string.Format("{0}", tempParam);
	return retVal;

Sample VB.NET (autogenerated)

Public Function CombineUri(ParamArray uriParams As String()) As String
	Dim retVal = String.Empty
	For Each uriParam As var In uriParams
		Dim tempParam = uriParam.Trim()
		If Not [String].IsNullOrEmpty(tempParam) Then
			tempParam = uriParam.TrimEnd("/"C, "\"C)
			retVal = If(Not [String].IsNullOrEmpty(retVal), String.Format("{0}/{1}", retVal, tempParam), String.Format("{0}", tempParam))
		End If
	Return retVal
End Function

For more informations about params see the msdn: params (C# Reference)

One thought on “How to combine multiple Uri in C# and VB.NET”

Leave a Reply