Replace part of URL using - c#

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

Related

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);

Load a web page to send data

Assume that I have a php script which saves get queries on info parameter. I have it as a string variable:
string url = "http://example.com/write.php?info="
Let's say I have a string like this:
string info = "asd";
So I want to load the web page without showing to user. The url will be url+info
How can i do that?
You can use WebClient:
var fullUrl = url + info;
var conent = new System.Net.WebClient().DownloadString(fullUrl);

Change String.Substring

string url = "www.google.com/?filter=xpto";
string domain = url.Contains('?')
? url.Substring(0, url.IndexOf('?'));
: url;
Is there a simpler way to do this w/o having to override Substring method?
You can write own extension method:
public static string GetDomain(this string url)
{
return url.Contains('?')
? url.Substring(0, url.IndexOf('?'));
: url;
}
Usage:
string domain = url.GetDomain();
You should also not use string methods if you work with Uris. Since your uri is somewhat malformed(f.e. it doesn't contain the protocol) it's a little bit more difficult to extract the domain:
string url = "www.google.com/?filter=xpto";
if (!url.Contains("://")) url = "http://" + url; // presume HTTP
string domain = url;
string host = url;
Uri uri;
if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri))
{
domain = uri.GetLeftPart(UriPartial.Authority); // http://www.google.com
host = uri.Host; // www.google.com, without protocol or port
}
Why don't you use Uri class instead ?
var url = new Uri("http://www.google.com/?filter=xpto");
var domain = url.Host;
Console.WriteLine(domain);

Get current URL but excluding some parts

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".

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.

Categories

Resources