Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending multiple segments with System.Uri

Tags:

c#

uri

var baseUri = new Uri("http://localhost/");
var uri1 = new Uri(baseUri, "1");
var uri2 = new Uri(uri1, "2");   

Unexpectedly, uri2 is http://localhost/2. How would I append to uri1 so it's http://localhost/1/2 intead? Does Uri do this, or do I need to fallback to strings? Incidentally, I've tried adding leading/trailing slashes almost everywhere.

like image 873
Daniel Avatar asked Apr 13 '12 21:04

Daniel


People also ask

How do I define additional segments in a URI?

Each additional segment begins at the first character after the preceding segment, and terminates with the next slash or the end of the path. (A URI's absolute path contains everything after the host and port and before the query and fragment.)

What is the absolute path and segments for two URIs?

(A URI's absolute path contains everything after the host and port and before the query and fragment.) The following example shows the absolute path and segments for two URIs. The second example illustrates that the fragment and query are not part of the absolute path and therefore are not segments. Section1.htm

How many examples of SYSTEM URI APPEND are there?

C# (CSharp) System Uri.Append - 11 examples found. These are the top rated real world C# (CSharp) examples of System.Uri.Append extracted from open source projects.

Is the segments property valid for relative URIs?

This instance represents a relative URI, and this property is valid only for absolute URIs. The following example creates a Uri instance with 3 segments and displays the segments on the screen. The Segments property returns an array of strings containing the "segments" (substrings) that form the URI's absolute path.


1 Answers

"1" and "2" are "file name portion" of a url. If you make "1" to look more like directory path it will work ok "1/":

var baseUri = new Uri("http://localhost/");
var uri1 = new Uri(baseUri, "1/");
var uri2 = new Uri(uri1, "2"); 

Note: "file name portion" is not a real term, as Url only have "path" and "query" component, but normally last chunk of a path is treated as file name: "/foo/bar/file.txt".

When you combine 2 path you want to replace some tail portion of the first path with the second one. In your case it ends up to have just "file name" segment for both :"/1" and "2" (if you put real value like "/myFile.txt" and "NewFile.txt" in combining it would be easier to see why it behaves this way).

like image 125
Alexei Levenkov Avatar answered Oct 05 '22 04:10

Alexei Levenkov