Whats the equivalent to System.IO.Path ?
I got this url: http://www.website.com/category1/category2/file.aspx?data=123
How can i break this down, like
var url = ASPNETPATH("http://www.website.com/category1/category2/file.aspx?data=123");
url.domain <-- this would then return http://www.website.com
url.folder <-- would return category1/category2
url.file <-- would return file.aspx
url.queryString <-- would return the querystring in some format
Use the UriBuilder class:
http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx
UriBuilder uriBuilder = new UriBuilder("http://www.somesite.com/requests/somepage.aspx?i=123");
string host = uriBuilder.Host; // www.somesite.com
string query = uriBuilder.Query; // ?i=123
string path = uriBuilder.Path; // /requests/somepage.aspx
Check out the URI Class you can get all of that information using that class.
Regular expressions are perfect to use for this.
Here's a link that has some nice info on using them.
http://www.regular-expressions.info/
Edit : I forgot C# has a URI class which you can use for this as well.
Related
User input the url string in a textbox and I need to add a string "cmd" if not available .
Please suggest how to achieve this,
string cmdUrl = AddPrefix("https://google.com");
static string AddPrefix(string inputUrl)
{
return formattedUrl;// want to return https://cmd.google.com if the string cmd not added already in url
}
First, you can parse your url using var parsedUrl = new Uri(inputUrl).
Then check if the host includes your substring like this: parsedUrl.Host.StartsWith("cmd")
If it does, return your original url else build your new one: $"{parsedUrl.Scheme}://cmd.{parsedUrl.Host}{parsedUrl.PathAndQuery}"
This is my string
string link = "http%3A%2F%2Feurocommunicator.ge%2Fgeo%2Fview_myth%2F229"
I want to get absolute uri but it throws exception that uri is invalid :
Uri uri = new Uri(link);
What's wrong in this sting?
i want to get something like this :
http://eurocommunicator.ge/geo/view_myth/229
You can use :
string decodedUrl = Uri.UnescapeDataString(url)
https://msdn.microsoft.com/en-us/library/system.uri.unescapedatastring(v=vs.110).aspx
Works like a charm in linqpad
void Main()
{
var url="http%3A%2F%2Feurocommunicator.ge%2Fgeo%2Fview_myth%2F229";
string decodedUrl = Uri.UnescapeDataString(url);
Console.WriteLine(decodedUrl);
}
You can try doing this:
Uri uri = new Uri("http://eurocommunicator.ge/geo/view_myth/229");
or
string link = "http%3A%2F%2Feurocommunicator.ge%2Fgeo%2Fview_myth%2F229"
Uri uri = new Uri(Server.UrlDecode(link));
Ok ok my fail HttpUtility.UrlDecode works fine, i was using HtmlDecode instead of it. How stupid am i
I want to write a little helper method which returns the base URL of the site. This is what I came up with:
public static string GetSiteUrl()
{
string url = string.Empty;
HttpRequest request = HttpContext.Current.Request;
if (request.IsSecureConnection)
url = "https://";
else
url = "http://";
url += request["HTTP_HOST"] + "/";
return url;
}
Is there any mistake in this, that you can think of? Can anyone improve upon this?
Try this:
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
Request.ApplicationPath.TrimEnd('/') + "/";
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority)
That's it ;)
The popular GetLeftPart solution is not supported in the PCL version of Uri, unfortunately. GetComponents is, however, so if you need portability, this should do the trick:
uri.GetComponents(
UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);
This is a much more fool proof method.
VirtualPathUtility.ToAbsolute("~/");
I believe that the answers above doesn't consider when the site is not in the root of the website.
This is a for WebApi controller:
string baseUrl = (Url.Request.RequestUri.GetComponents(
UriComponents.SchemeAndServer, UriFormat.Unescaped).TrimEnd('/')
+ HttpContext.Current.Request.ApplicationPath).TrimEnd('/') ;
To me, #warlock's looks like the best answer here so far, but I've always used this in the past;
string baseUrl = Request.Url.GetComponents(
UriComponents.SchemeAndServer, UriFormat.UriEscaped)
Or in a WebAPI controller;
string baseUrl = Url.Request.RequestUri.GetComponents(
UriComponents.SchemeAndServer, UriFormat.Unescaped)
which is handy so you can choose what escaping format you want. I'm not clear why there are two such different implementations, and as far as I can tell, this method and #warlock's return the exact same result in this case, but it looks like GetLeftPart() would also work for non server Uri's like mailto tags for instance.
I go with
HttpContext.Current.Request.ServerVariables["HTTP_HOST"]
Based on what Warlock wrote, I found that the virtual path root is needed if you aren't hosted at the root of your web. (This works for MVC Web API controllers)
String baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority)
+ Configuration.VirtualPathRoot;
I'm using following code from Application_Start
String baseUrl = Path.GetDirectoryName(HttpContext.Current.Request.Url.OriginalString);
This works for me.
Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, "") + Request.ApplicationPath;
Request.Url.OriginalString: return the complete path same as browser showing.
Request.Url.PathAndQuery: return the (complete path) - (domain name + PORT).
Request.ApplicationPath: return "/" on hosted server and "application name" on local IIS deploy.
So if you want to access your domain name do consider to include the application name in case of:
IIS deployment
If your application deployed on the sub-domain.
====================================
For the dev.x.us/web
it return this
strong text
Please use the below code
string.Format("{0}://{1}", Request.url.Scheme, Request.url.Host);
you could possibly add in the port for non port 80/SSL?
something like:
if (HttpContext.Current.Request.ServerVariables["SERVER_PORT"] != null && HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString() != "80" && HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString() != "443")
{
port = String.Concat(":", HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString());
}
and use that in the final result?
I have the following code snippet:
string tmp = String.Format("<SCRIPT FOR='window' EVENT='onload' LANGUAGE='JavaScript'>javascript:window.open('{0}');</SCRIPT>", url);
ClientScript.RegisterClientScriptBlock(this.GetType(), "NewWindow", tmp);
The URL generated by this code include the port number and I think that is happening because port 80 is used by the website and in this code I am trying to load a page from a virtual directory of the website. Any ideas on how to suppress the port number in the URL string generated by this code?
Use the Uri.GetComponents method. To remove the port component you'll have to combine all the other components, something like:
var uri = new Uri( "http://www.example.com:80/dir/?query=test" );
var clean = uri.GetComponents( UriComponents.Scheme |
UriComponents.Host |
UriComponents.PathAndQuery,
UriFormat.UriEscaped );
EDIT: I've found a better way:
var clean = uri.GetComponents( UriComponents.AbsoluteUri & ~UriComponents.Port,
UriFormat.UriEscaped );
UriComponents.AbsoluteUri preservers all the components, so & ~UriComponents.Port will only exclude the port.
UriBuilder u1 = new UriBuilder( "http://www.example.com:80/dir/?query=test" );
u1.Port = -1;
string clean = u1.Uri.ToString();
Setting the Port property to -1 on UriBuilder will remove any explicit port and implicitly use the default port value for the protocol scheme.
A more generic solution (works with http, https, ftp...) based on Ian Flynn idea.
This method does not remove custom port, if any.
Custom port is defined automatically depending on the protocol.
var uriBuilder = new UriBuilder("http://www.google.fr/");
if (uriBuilder.Uri.IsDefaultPort)
{
uriBuilder.Port = -1;
}
return uriBuilder.Uri.AbsoluteUri;
April 2021 update
With newer .NET versions, Uri.AbsoluteUri removes the default ports and retains the custom port by default. The above code-snippet is equivalent to:
var uriBuilder = new UriBuilder("http://www.google.fr/");
return uriBuilder.Uri.AbsoluteUri;
I would use the System.Uri for this. I have not tried, but it seems it's ToString will actually output what you want:
var url = new Uri("http://google.com:80/asd?qwe=asdff");
var cleanUrl = url.ToString();
If not, you can combine the components of the url-members to create your cleanUrl string.
var url = "http://google.com:80/asd?qwe=zxc#asd";
var regex = new Regex(#":\d+");
var cleanUrl = regex.Replace(url, "");
the solution with System.Uri is also possible but will be more bloated.
You can use the UriBuilder and set the value of the port to -1
and the code will be like this:
Uri tmpUri = new Uri("http://LocalHost:443/Account/Index");
UriBuilder builder = new UriBuilder(tmpUri);
builder.Port = -1;
Uri newUri = builder.Uri;
You can also use the properties of URIBuilder for this, it has properties for outputting an url the way you want
Ok, thanks I figured it out...used the KISS principle...
string redirectstr = String.Format(
"http://localhost/Gradebook/AcademicHonestyGrid.aspx?StudentID={0}&ClassSectionId={1}&uid={2}",
studid,
intSectionID,
HttpUtility.UrlEncode(encrypter.Encrypt(uinfo.ToXml())));
Response.Redirect(redirectstr );
works fine for what I am doing which is a test harness
Given an absolute URI/URL, I want to get a URI/URL which doesn't contain the leaf portion. For example: given http://foo.com/bar/baz.html, I should get http://foo.com/bar/.
The code which I could come up with seems a bit lengthy, so I'm wondering if there is a better way.
static string GetParentUriString(Uri uri)
{
StringBuilder parentName = new StringBuilder();
// Append the scheme: http, ftp etc.
parentName.Append(uri.Scheme);
// Appned the '://' after the http, ftp etc.
parentName.Append("://");
// Append the host name www.foo.com
parentName.Append(uri.Host);
// Append each segment except the last one. The last one is the
// leaf and we will ignore it.
for (int i = 0; i < uri.Segments.Length - 1; i++)
{
parentName.Append(uri.Segments[i]);
}
return parentName.ToString();
}
One would use the function something like this:
static void Main(string[] args)
{
Uri uri = new Uri("http://foo.com/bar/baz.html");
// Should return http://foo.com/bar/
string parentName = GetParentUriString(uri);
}
Thanks,
Rohit
Did you try this? Seems simple enough.
Uri parent = new Uri(uri, "..");
This is the shortest I can come up with:
static string GetParentUriString(Uri uri)
{
return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length);
}
If you want to use the Last() method, you will have to include System.Linq.
There must be an easier way to do this with the built in uri methods but here is my twist on #unknown (yahoo)'s suggestion.
In this version you don't need System.Linq and it also handles URIs with query strings:
private static string GetParentUriString(Uri uri)
{
return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments[uri.Segments.Length -1].Length - uri.Query.Length);
}
Quick and dirty
int pos = uriString.LastIndexOf('/');
if (pos > 0) { uriString = uriString.Substring(0, pos); }
Shortest way I found:
static Uri GetParent(Uri uri) {
return new Uri(uri, Path.GetDirectoryName(uri.LocalPath) + "/");
}
PapyRef's answer is incorrect, UriPartial.Path includes the filename.
new Uri(uri, ".").ToString()
seems to be cleanest/simplest implementation of the function requested.
I read many answers here but didn't find one that I liked because they break in some cases.
So, I am using this:
public Uri GetParentUri(Uri uri) {
var withoutQuery = new Uri(uri.GetComponents(UriComponents.Scheme |
UriComponents.UserInfo |
UriComponents.Host |
UriComponents.Port |
UriComponents.Path, UriFormat.UriEscaped));
var trimmed = new Uri(withoutQuery.AbsoluteUri.TrimEnd('/'));
var result = new Uri(trimmed, ".");
return result;
}
Note: It removes the Query and the Fragment intentionally.
new Uri(uri.AbsoluteUri + "/../")
Get segmenation of url
url="http://localhost:9572/School/Common/Admin/Default.aspx"
Dim name() As String = HttpContext.Current.Request.Url.Segments
now simply using for loop or by index, get parent directory name
code = name(2).Remove(name(2).IndexOf("/"))
This returns me, "Common"
Thought I'd chime in; despite it being almost 10 years, with the advent of the cloud, getting the parent Uri is a fairly common (and IMO more valuable) scenario, so combining some of the answers here you would simply use (extended) Uri semantics:
public static Uri Parent(this Uri uri)
{
return new Uri(uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length - uri.Query.Length).TrimEnd('/'));
}
var source = new Uri("https://foo.azure.com/bar/source/baz.html?q=1");
var parent = source.Parent(); // https://foo.azure.com/bar/source
var folder = parent.Segments.Last(); // source
I can't say I've tested every scenario, so caution advised.