Get individual query parameters from Uri [duplicate] - c#

This question already has answers here:
Get URL parameters from a string in .NET
(17 answers)
Closed 4 years ago.
I have a uri string like: http://example.com/file?a=1&b=2&c=string%20param
Is there an existing function that would convert query parameter string into a dictionary same way as ASP.NET Context.Request does it.
I'm writing a console app and not a web-service so there is no Context.Request to parse the URL for me.
I know that it's pretty easy to crack the query string myself but I'd rather use a FCL function is if exists.

Use this:
string uri = ...;
string queryString = new System.Uri(uri).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
This code by Tejs isn't the 'proper' way to get the query string from the URI:
string.Join(string.Empty, uri.Split('?').Skip(1));

You can use:
var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)
MSDN

This should work:
string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters =
System.Web.HttpUtility.ParseQueryString(querystring);
According to MSDN. Not the exact collectiontype you are looking for, but nevertheless useful.
Edit: Apparently, if you supply the complete url to ParseQueryString it will add 'http://example.com/file?a' as the first key of the collection. Since that is probably not what you want, I added the substring to get only the relevant part of the url.

I had to do this for a modern windows app. I used the following:
public static class UriExtensions
{
private static readonly Regex _regex = new Regex(#"[?&](\w[\w.]*)=([^?&]+)");
public static IReadOnlyDictionary<string, string> ParseQueryString(this Uri uri)
{
var match = _regex.Match(uri.PathAndQuery);
var paramaters = new Dictionary<string, string>();
while (match.Success)
{
paramaters.Add(match.Groups[1].Value, match.Groups[2].Value);
match = match.NextMatch();
}
return paramaters;
}
}

Have a look at HttpUtility.ParseQueryString() It'll give you a NameValueCollection instead of a dictionary, but should still do what you need.
The other option is to use string.Split().
string url = #"http://example.com/file?a=1&b=2&c=string%20param";
string[] parts = url.Split(new char[] {'?','&'});
///parts[0] now contains http://example.com/file
///parts[1] = "a=1"
///parts[2] = "b=2"
///parts[3] = "c=string%20param"

For isolated projects, where dependencies must be kept to a minimum, I found myself using this implementation:
var arguments = uri.Query
.Substring(1) // Remove '?'
.Split('&')
.Select(q => q.Split('='))
.ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());
Do note, however, that I do not handle encoded strings of any kind, as I was using this in a controlled setting, where encoding issues would be a coding error on the server side that should be fixed.

In a single line of code:
string xyz = Uri.UnescapeDataString(HttpUtility.ParseQueryString(Request.QueryString.ToString()).Get("XYZ"));

Microsoft Azure offers a framework that makes it easy to perform this.
http://azure.github.io/azure-mobile-services/iOS/v2/Classes/MSTable.html#//api/name/readWithQueryString:completion:

You could reference System.Web in your console application and then look for the Utility functions that split the URL parameters.

Related

Extracting a URL in the query part of another URL [duplicate]

This question already has answers here:
Get URL parameters from a string in .NET
(17 answers)
Closed 9 years ago.
How can I extract a valid URL from a string like this one
h*tps://www.google.com/url?q=h*tp://www.site.net/file.doc&sa=U&ei=_YeOUc&ved=0CB&usg=AFQjCN-5OX
I want to extract this part: h*tp://www.site.net/file.doc, this is my valid URL.
Add System.Web.dll assembly and use HttpUtility class with static methods.
Example:
using System;
using System.Web;
class MainClass
{
public static void Main (string[] args)
{
Uri uri = new Uri("https://www.google.com/url?q=http://www.site.net/file.doc&sa=U&ei=_YeOUc&ved=0CB&usg=AFQjCN-5OX");
Uri doc = new Uri (HttpUtility.ParseQueryString (uri.Query).Get ("q"));
Console.WriteLine (doc);
}
}
I don't know what your other strings can look like, but if your 'valid URL' is between the first = and the first &, you could use:
(?<==).*?(?=&)
It basically looks for the first = and matches anything before the next &.
Tested here.
You can use split function
string txt="https://www.google.com/url?q=http://www.site.net/file.doc&sa=U&ei=_YeOUc&ved=0CB&usg=AFQjCN-5OX";
txt.split("?q=")[1].split("&")[0];
in this particular case with the string you posted you can do this:
string input = "your URL";
string newString = input.Substring(36, 22) ;
But if the length of the initial part of the URL changes, and also the lenght of the part you like to extract changes, then would not work.

Count QueryString Key in string of URL

I want to count how many query string key appear in a string of URL. The URL here is an string so I can't use Request.QueryString.AllKeys to count how many key in the url. Currently, I have an solution for this by analyze the structure of url string and using count string within a string to count query string keys in an url string. Everyone can look clearly in my sample of code:
public int CountQueryStringKey(string urlString)
{
string urlWithoutKey = urlString.Substring(0, urlString.IndexOf("?"));
string allKeyString = urlString.Substring(urlString.IndexOf("?") + 1);
string[] allKeyAndValue = allKeyString.Split('&');
return allKeyAndValue.Length;
}
It is simple but not enough. What will happen if there is no query string key in string of url, and there are always different kind of url which I'm not sure it's structure.
I need some help for a good solution in this issue.
While duplicate (Get individual query parameters from Uri) provides good enough answer I'd suggest using Uri.Query to extract query portion of the Url. Than continue with HttpUtility.ParseQueryString as recommended in other question.
Than NameValueCollection.Count to get the number of query parameters.
var queryParameters = HttpUtility.ParseQueryString(new Uri(urlString).Query);
var numberOfParameter = queryParameters.Count;
Have a look at this post. Here you can use HttpUtility to get query string parameters from the normal string
HttpUtility

Regular expression to get base url

I got a very long string that cointains querystrings and and some regular site urls in it. it looks something like
http://www.mysite.com/site/site?pageId=1234&otherId=4321
I would like to get just the http://www.mysite.com from this string. Im thinking maybe a regular expression could do the trick, but Im def not quilfied to write any of that :) so could i get some help?
EDIT
i need a solution so i can pass url string and get the base url from that. Not my current Url
thanks guys, appreciate it as always.
Please try this:
string uri = Request.Url.GetLeftPart(UriPartial.Authority);
You can check with this also:
var url = new Uri("http://www.mysite.com/site/site?pageId=1234&otherId=4321");
string uri = url.GetLeftPart(UriPartial.Authority);
Solution
var url = new Uri("http://www.mydomain.com/Site/Subsite?page=site");
var baseUrl = url.Host;
As the author asked for a regular expression, that's it:
static string ExtractBaseUrl(string url)
{
Regex regex = new Regex(#"^https?:\/\/[^\/]+");
Match resultm = regex.Match(url);
if (resultm.Success)
return resultm.Groups[0].Value;
else return null;
}

Need help about Regular Expression Syntax

I tried to take only this part(after the "j&q") from link
(http://www.google.com/aclk?sa=lai=CEvAD5thCTfHPCIq5gwe2lOWKD6n_uOIB4bzDkxm8uIhRCAAQASDrxZ0GKANQgI6s1ANgybblirSk2A-gAYem9NwDyAEBqQLN5n97JxulPqoEGk_QITE_eyPbZTKIyNFl8dQhptl05oxQ2fHjgAWQTg&sig=AGiWqtwLGY6f1Gnci0e0ojoRsLBxr9joLg&adurl=http://www.mediterraholidays.com/egypt/cairo-and-nile-cruise&rct=j&q=egpyt%20package%20trips).
I used ^.*q=.*$ but with this. I need only after the j&q part if it has.
Why don't you use System.Uri class for this:
Uri url = new Uri("http://www.google.com/aclk?sa=lai=CEvAD5thCTfHPCIq5gwe2lOWKD6n_uOIB4bzDkxm8uIhRCAAQASDrxZ0GKANQgI6s1ANgybblirSk2A-gAYem9NwDyAEBqQLN5n97JxulPqoEGk_QITE_eyPbZTKIyNFl8dQhptl05oxQ2fHjgAWQTg&sig=AGiWqtwLGY6f1Gnci0e0ojoRsLBxr9joLg&adurl=http://www.mediterraholidays.com/egypt/cairo-and-nile-cruise&rct=j&q=egpyt%20package%20trips");
var queryString = HttpUtility.ParseQueryString(url.Query);
var q = queryString["q"];
The q variable holds the value: egpyt package trips
&q=(?<data>[^&]*)
The answer needs to be at least 30 chars, so I add some joke:
“Knock, knock.”
“Who’s there?”
very long pause….
“Java.”

trim url string. c#

how can i trim a youtube url so it only returns the video id for example http://www.youtube.com/watch?v=VPqTW-9U9nU. how would i return VPqTW-9U9nU. this has to be for several url inputted. I would like to use regex but I do not understand it at all. so if somebody has a solution with regex could you explain it in abit more details :)
Without doing any string manipulation you can use Uri and ParseQueryString
Uri uri = new Uri("http://www.youtube.com/watch?v=VPqTW-9U9nU");
var s = HttpUtility.ParseQueryString(uri.Query).Get("v");
No RegEx needed in this case:
string url = "http://www.youtube.com/watch?v=VPqTW-9U9nU";
string videoId = url.Substring(url.IndexOf("?v=") + 3);
Why not just stick with something simple?
string youTubeUrl = "http://www.youtube.com/watch?v=VPqTW-9U9nU";
string id = youTubeUrl.Replace("http://www.youtube.com/watch?v=", String.Empty);
Regular expressions are handy, but sometimes overkill and can make your code harder to understand when you use them in places you don't need them.
Try something like this:
string url = "http://www.youtube.com/watch?v=VPqTW-9U9nU";
string video_id = url.Substring(0,url.LastIndexOf("=')+1);
The other answers look right, too.
You could also use String.Split():
url.Split(new[] { '=' }, 2)[1]

Categories

Resources