Coming from this question, i'm looking for a way to cascade a url like Path.Combine for file system does including a path-parameter.
My input are the following 3 parameters:
string host = "test.com"; //also possilbe: "test.com/"
string path = "/foo/"; //also possilbe: "foo", "/", "","/foo","foo/"
string file = "test.temp"; //also possilbe: "/test.temp"
The expected result is
http://test.com/foo/test.temp
This approach is the best I could find but it does'n work for all cases:
Uri myUri = new Uri(new Uri("http://" + host +"/"+ path), file);
You could try using Uri.TryCreate():
Uri uri;
bool success = Uri.TryCreate(new Uri("http://" + host), path.Trim('/') + "/" + file.Trim('/'), out uri);
This will return false if the url is somehow in an incorrect format. However, if you are sure the format is correct, you can just use the Uri constructor:
var uri = new Uri(new Uri("http://" + host), path.Trim('/') + "/" + file.Trim('/'));
You can use the UriBuilder class + IO.Path.Combine for the Path:
var builder = new UriBuilder();
builder.Host = host.Trim('/');
builder.Path = Path.Combine(path.Trim('/'), file.Trim('/'));
string result = builder.ToString(); // "http://test.com/foo/test.temp"
If you want the Uri-inctance just use the Uri-property of the UriBuilder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With