Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cascade a url string

Tags:

string

c#

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);
like image 987
fubo Avatar asked Sep 10 '26 19:09

fubo


2 Answers

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('/'));
like image 54
Henk Mollema Avatar answered Sep 12 '26 09:09

Henk Mollema


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.

like image 38
Tim Schmelter Avatar answered Sep 12 '26 10:09

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!