Get current URL but excluding some parts - c#

The current URL looks like: http://mycompany.com/jobs/java-developer.aspx#.U9-RH2OTLfA
I need to get the part before the #, so it's gonna be: http://mycompany.com/jobs/java-developer.aspx
How can I do that in code behind?

You can use Uri class:
var uri = new Uri("http://mycompany.com/jobs/java-developer.aspx#.U9-RH2OTLfA");
var result = uri.GetLeftPart(UriPartial.Path);

string url = "http://mycompany.com/jobs/java-developer.aspx#.U9-RH2OTLfA";
string path = url.Substring(0, url.IndexOf("#"));

Uri myUri = new Uri("http://mycompany.com/jobs/java-developer.aspx#.U9-RH2OTLfA");
string url = myUri.Host + myUri.LocalPath;
you can create uri with string then get the parts

private String getGoodString(String url)
{
return url.Substring(0, url.IndexOf("#") - 1);
}
This will return everything up to but not including the # symbol in your string. Assuming you have a # to signal when to stop getting the string of the URL. Otherwise if there are multiple #. You can use lastIndexOf, or firstIndexOf if you need to "trim the fat".

Related

Replace part of URL using

I have a url that looks like this
https://domain1.com/go/2345/Default.aspx?c%7c2vCZVIjuUzLTfgsgagasgsgasgsagag
I would like to be able to replace the domain1.com for domain12.com so it would look like this
https://domain12.com/go/2453545/Default.aspx?
How I can replace only the domain1.com part? Quick note : Everything after the "go/"changes every time I open the browser
I try this
I get the Url from the browser
string getUrl = Url;
then I replace the value
string newUrl = getUrl .Replace(getUrl .Substring(url.IndexOf(go)
var u = "https://domain1.com/go/2345/Default.aspx?c%7c2vCZVIjuUzLTfgsgagasgsgasgsagag";
var uri = new Uri(u);
var path =
uri.PathAndQuery.Substring(0, uri.PathAndQuery.Length - uri.Query.Length);
string newUrl = "https://domain2.com" + path;
Console.WriteLine(newUrl);
// OUTPUT: https://domain2.com/go/2345/Default.aspx

Add Query String if not Exist without Request

I don't have the Request, I only have a url string. Also, the url can either be relative or absolute. And since Uri and UriBuilder do not support relative urls, I'll probably have to do it manually, unless there is a trick I'm not aware of. This method will be used in probably more than a thousand lines of code in my project that's why I'd like to do it right.
The following code will break if a relative url is passed:
public static string AddQueryStringIfNotExists(string url, string parameter, string value)
{
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
if (query[parameter] == null)
{
query[parameter] = value;
uriBuilder.Query = query.ToString();
}
return uriBuilder.ToString();
}
P.S. I'm fine with doing it manually by checking whether my parameter appears after the first ? but that would require tackling several edge cases, the thing I'm trying to avoid (like a parameter name contained in another parameter)
Just check that your url is absolute. If it's not convert it to an absolute url.
Then use HttpUtility.ParseQueryString to parse the query string and add your parameter if needed.
Convert the UriBuilder back into a Uri.
If the input was an absolute Uri return the entire Uri. If the input was relative then return the relative uri.
private static Uri dummy = new Uri("http://dummy/");
public static string AddQueryStringIfNotExists(string url, string parameter, string value)
{
var uri = new Uri(url, UriKind.RelativeOrAbsolute);
var uriBuilder = uri.IsAbsoluteUri ? new UriBuilder(url) : new UriBuilder(new Uri(dummy, url));
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
if (query[parameter] == null)
{
query[parameter] = value;
uriBuilder.Query = query.ToString();
}
return uri.IsAbsoluteUri ? uriBuilder.ToString() : dummy.MakeRelativeUri(new Uri(uriBuilder.ToString())).ToString();
}
Example:
string s = AddQueryStringIfNotExists("somedirectory/mypage/html?something=1", "somethingelse", "1");
Output:
somedirectory/mypage/html?something=1&somethingelse=1
There can be a simple helper which will transform relative URL to absolute:
public static string ToAbsoluteUrl(this string url, string domain)
{
var result = url.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? url : domain + url;
return result;
}
url = "/page?skip=0";
url = url.ToAbsoluteUrl("https://example.com"); // https://example.com/page?skip=0
var uriBuilder = new UriBuilder(url);

How to get the parameter from a relative URL string in C#?

What's the most efficient way to get a specific parameter from a relative URL string using C#?
For example, how would you get the value of the ACTION parameter from the following relative URL string:
string url = "/page/example?ACTION=data&FOO=test";
I have already tried using:
var myUri = new Uri(url, UriKind.Relative);
String action = HttpUtility.ParseQueryString(myUri.Query).Get("ACTION");
However, I get the following error:
This operation is not supported for a relative URI.
int idx = url.IndexOf('?');
string query = idx >= 0 ? url.Substring(idx) : "";
HttpUtility.ParseQueryString(query).Get("ACTION");
While many of the URI operations are unavailable for UriKind.Relative (for whatever reason), you can build a fully qualified URI through one of the overloads that takes in a Base URI
Here's an example from the docs on Uri.Query:
Uri baseUri = new Uri ("http://www.contoso.com/");
Uri myUri = new Uri (baseUri, "catalog/shownew.htm?date=today");
Console.WriteLine(myUri.Query); // date=today
You can also get the current base from HttpContext.Current.Request.Url or even just create a mock URI base with "http://localhost" if all you care about is the path components.
So either of the following approaches should also return the QueryString from a relative path:
var path = "catalog/shownew.htm?date=today"
var query1 = new Uri(HttpContext.Current.Request.Url, path).Query;
var query2 = new Uri(new Uri("http://localhost"), path).Query;

How to download file in C# with its name?

I'm trying to download file from URL using WebClient, the problem is that the function .DownloadFile() requiring URL, and name that will be given to the saved file, but when we access to the URL it already has the file name.
How can I keep the file name as it is in the URL?
This should work if I understand your question correctly:
private string GetFileNameFromUrl(string url)
{
if(string.IsNullOrEmpty(url))
return "image.jpg"; //or throw an ArgumentException
int sepIndex = url.LastIndexOf("/");
if(sepIndex == -1)
return "image.jpg"; //or throw an ArgumentException
return url.Substring(sepIndex);
}
Then you can use it like so:
string uri = "http://www.mywebsite.com/res/myimage.jpg";
WebClient client = new WebClient();
client.DownloadFile(uri, this.GetFileNameFromUrl(uri));
If you have no control over the url itself you might want to do some validation on it e.g. Regex.
Instead of parsing the url I suggest using function Path.GetFileName():
string uri = "http://yourserveraddress/fileName.txt";
string fileName = System.IO.Path.GetFileName(uri);
WebClient client = new WebClient();
client.DownloadFile(uri, fileName);
What about:
string url = "http://www.mywebsite.com/res/myimage.jpg?guid=2564";
Uri uri = new Uri(url);
string fileName = uri.Segments.Last();
Note: Last() is the extension method from Linq.

How do I decode a URL parameter using C#?

How can I decode an encoded URL parameter using C#?
For example, take this URL:
my.aspx?val=%2Fxyz2F
string decodedUrl = Uri.UnescapeDataString(url)
or
string decodedUrl = HttpUtility.UrlDecode(url)
Url is not fully decoded with one call. To fully decode you can call one of this methods in a loop:
private static string DecodeUrlString(string url) {
string newUrl;
while ((newUrl = Uri.UnescapeDataString(url)) != url)
url = newUrl;
return newUrl;
}
Server.UrlDecode(xxxxxxxx)
Have you tried HttpServerUtility.UrlDecode or HttpUtility.UrlDecode?
Try:
var myUrl = "my.aspx?val=%2Fxyz2F";
var decodeUrl = System.Uri.UnescapeDataString(myUrl);
Try this:
string decodedUrl = HttpUtility.UrlDecode("my.aspx?val=%2Fxyz2F");

Categories

Resources