Split string (Uri path) based on "/"

I wonder if anyone can point me in the right direction. What I would like to achieve is to split the line based on the fact that it has a "/". For example, if I had: www.site.com/course/123456/216 in code (C #), I would like to be able to split the line in the code so that 123456 can be assigned to param1 and assign 216 to param2 (course - this is the "friendly" page name). If I had to add the third line '/' to the line, I would like it to become param3, etc. Etc.

Ideally, I would like to be able to put this code somewhere so that I can enable it depending on which user controls it will need.

+14
c # query-string
source share
6 answers

Uri.Segments maybe what you are looking for:

new Uri("http://www.contoso.com/foo/bar/index.htm#search").Segments 

Results in [ "/", "foo/", "bar/", "index.html" ]

+23
source share

Why not just use split?

 var valueArray = "www.site.com/course/123456/216".Split('/'); 

The entire line will be split in the array

index 0 will be "www.site.com" etc.

+7
source share
 HttpContext.Current.Request.Url.AbsolutePath.Split('/') 
+3
source share

So, making an assumption that do not have / in them:

 var splitVals = queryString.Split('/'); var vals = new Dictionary<string, string>(); for (int i = 2; i <= splitVals.Count; i++) { vals.Add(string.Format("param{0}", i), vals[i]); } 

This will get you started. Now, if you want to set them to real variables, you will need to do some reflection and use reflection, but your question is not close enough to make any real assumptions.

EDIT

To make this code reusable, I would build an extension method:

 namespace System { public static class StringExtensions { public static Dictionary<string, string> SplitQueryString(this string queryString) { var splitVals = queryString.Split('/'); var vals = new Dictionary<string, string>(); for (int i = 2; i <= splitVals.Count; i++) { vals.Add(string.Format("param{0}", i), vals[i]); } return vals; } } } 

because then you can do this:

 var vals = queryString.SplitQueryString(); 
+2
source share

http://msdn.microsoft.com/en-us/library/b873y76a.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

string QueryString = "1234/567/890"; string[] QueryArray = QueryString.Split('/');

Now QueryArray[0] = 1234 , QueryArray[1] = 567 , QueryArray[2] = 890 ,

+1
source share

url: server/func2/SubFunc2

// Get path components. Separator clutch. Returns {"/", "func2 /", "sunFunc2"}. string[] pathsegments = myUri.Segments;

+1
source share

All Articles