How to get a relative url from an absolute Url programmaticaly? - c#

I'm given an absolute URL, like this: http://pc6/Surveys/Lists/Survey list
How can I take that transform it into a relative URL?
This is what I've tried, but it doesn't seem to work.
foreach (SPListItem item in itemCollections)
{
string Url = item["URL"].ToString();
string[] url = Url.Split(',');
var listUrl = url[0]; //Here I Got Absolute Url
}

I guess it depends on what you want it relative to, but assuming you're just looking for an absolute path...
string absolute = "http://example.com/this/is/a/test";
string rel = new Uri(absolute).AbsolutePath;
or with the query,
string rel = new Uri(absolute).PathAndQuery;
Admittedly I'm also a little confused about your attempt. Why are you splitting by a comma? Are we, perhaps, not on the same page about what a relative path should look like? In any event, this should do it.

Related

Remove the first and last parts of a URL string from AbsolutePath in ASP.NET

I'm not good with manipulating strings and could use a little help.
I'd have a URL (http://localhost/mySite/default.aspx) and I have the AbsolutePath as a string that I'm working with (/mySite/default.aspx):
string mySubUrl = Request.Url.AbsolutePath;
What I'm trying to do is remove the first and last parts of the AbsolutePath. In this example, removing "mySite" and "default.aspx", which would leave me with just "/".
There also may be instances where the URL is longer or shorter, e.g., http://localhost/mySite/mySubFolder/default.aspx, in which case after removing the first and last parts of the AbsolutePath I would be left with '/mySubFolder/'.
I did try working a little with Uri segments but didn't get too far:
string absolutePath = Request.Url.AbsolutePath;
Uri uri = new Uri(absolutePath);
string[] pathSegments = uri.Segments;
Quick solution:
string[] pathSegments = Request.Url.Segments.Skip(1).Take(Request.Url.Segments.Length - 2).ToArray();
The Request.Url.AbsolutePath already removes the left part of the Url for you, so it will give you something like /subSection/subFolder/default.aspx.
Then, you can remove the last part like this:
string absolutePath = Request.Url.AbsolutePath;
string[] urlSegments = absolutePath.Split('/');
urlSegments = urlSegments.Skip(1).Take(urlSegments.Length - 2);
string url = string.Join("/", urlSegments);

convert path into absolute url

I have a part of URL like below:
"employee/employeeDetail.aspx"
And the base path of the whole URL is:
"example.com/siteName"
And the desired output should be:
"http://www.example.com/siteName/employee/employeeDetail.aspx"
I've tried the below:
page.ResolveClientUrl(#"/employee/employeeDetail.aspx");
But the result was
"/employee/employeeDetail.aspx"
Instead of combining the two strings i.e.
string baseURL = #"example.com/siteName";
string relativeURL = #"employee/employeeDetail.aspx";
string finalURL = baseURL + relativeURL;
Are there any other better ways to form a URL?
I've tried adding ~ before the baseURL
page.ResolveClientUrl(#"~/employee/employeeDetail.aspx");
But the outcome was
../employee/employeeDetail.aspx
Generally, it's best to take a look at the incoming request and to build from that...
var ub = new UriBuilder(Request.Url);
var someNewPath = HostingEnvironment.MapPath("~/app/relative/path");
ub.Path = someNewPath;
ub.Query = perhapsAQueryString;
var absoluteUri = ub.Uri;
...but sometimes when you're behind a load-balancer, things might get more complicated, and you have to look at headers added by the load-balancer, such as X-REQUESTED-FOR
You need to tell the method that your url is relative from the application root path by adding the ~ at the beginning:
page.ResolveClientUrl(#"~/employee/employeeDetail.aspx");
If you don't do that, it will be resolved as absolute path from the root of your webserver.
you missed '~' symbol
tilde (~) to indicate the root.
page.ResolveClientUrl(#"~/employee/employeeDetail.aspx");

How to delete string from another string position in c#

I have two string:
string url = HttpContext.Current.Request.Url.AbsoluteUri;
//give me :
//url = http://localhost:1302/TESTERS/Default6.aspx?tabindex=2&tabid=15
And:
string path = HttpContext.Current.Request.Url.AbsolutePath;
//give me:
//path = /TESTERS/Default6.aspx
Now I want to get the string:
http://localhost:1302
So what I am thinking of is I will find the position of path in url and remove the sub-string from this position in url.
What I tried:
string strApp = url.Remove(url.First(path));
or
string strApp = url.Remove(url.find_first_of(path));
but I can't find the write way to express this idea. How can I archive my goal?
So basically you want the URL, from the start up to the beginning of your path.
You don't need to "remove" that part, only take characters up to that precise point. First, you can get that location with a simple IndexOf as it returns the position of the first character that matches your string. After this, simply take the part of url that goes from 0 to that index with Substring.
string url = "http://localhost:1302/TESTERS/Default6.aspx?tabindex=2&tabid=15";
string path = "/TESTERS/Default6.aspx";
int indexOfPath = url.IndexOf(path);
string strApp = url.Substring(0, indexOfPath); // gives http://localhost:1302
Which you can shorten to
string strApp = url.Substring(0, url.IndexOf(path));
you can also do something like below code to get the Host of URI
Uri uri =HttpContext.Current.Request.Url.AbsoluteUri ;
string host = uri.Authority; // "example.com"
Here is another option.. this doesn't require any string manipulation:
new Uri(HttpContext.Current.Request.Url, "/").AbsoluteUri
It generates a new Uri which is the path "/" relative to the original Url
You should just use this instead:
string baseURL = HttpContext.Current.Context.Request.Url.Scheme + "://" +
HttpContext.Current.Context.Request.Url.Authority;
This should not be solved using string manipulation. HttpContext.Current.Request.Url returns an Uri object which has capabilities to return the information you request.
var requestUrl = HttpContext.Current.Request.Url;
var result = requestUrl.GetComponents(UriComponents.SchemeAndServer,
UriFormat.Unescaped);
// result = "http://localhost:1302"

How to cut out a part of a path?

I want to cut out a part of a path but don't know how.
To get the path, I use this code:
String path = System.IO.Path.GetDirectoryName(fullyQualifiedName);
(path = "Y:\Test\Project\bin\Debug")
Now I need the first part without "\bin\Debug".
How can I cut this part out of the current path?
If you know, that you don't need only "\bin\Debug" you could use replace:
path = path.Replace("\bin\Debug", "");
or
path = path.Remove(path.IndexOf("\bin\Debug"));
If you know, that you don't need everything, after second \ you could use this:
path = path.Remove(path.LastIndexOfAny(new char[] { '\\' }, path.LastIndexOf('\\') - 1));
and finally, you could Take so many parts, how many you want like this:
path = String.Join(#"\", path.Split('\\').Take(3));
or Skip so many parts, how many you need:
path = String.Join(#"\", path.Split('\\').Reverse().Skip(2).Reverse());
You can use the Path class and a subsequent call of the Directory.GetParent method:
String dir = Path.GetDirectoryName(fullyQualifiedName);
string root = Directory.GetParent(dir).FullName;
You can do it within only 3 lines.
String path= #"Y:\\Test\\Project\\bin\\Debug";
String[] extract = Regex.Split(path,"bin"); //split it in bin
String main = extract[0].TrimEnd('\\'); //extract[0] is Y:\\Test\\Project\\ ,so exclude \\ here
Console.WriteLine("Main Path: "+main);//get main path
You can obtain the path of the parent folder of your path like this:
path = Directory.GetParent(path);
In your case, you'd have to do it twice.

Taking params from a url

Take these two URLs:
www.mySite.com?name=ssride360
www.mySite.com/ssride360
I know that to get the name param from url 1 you would do:
string name = Request.Params['name'];
But how would I get that for the second url?
I was thinking about attempting to copy the url and remove the known information (www.mySite.com) and then from there I could set name to the remainder.
How would I do a url copy like that? Is there a better way to get 'ssride360' from the second url?
Edit Looking on SO I found some info on copying URLs
string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx
string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx
Is this the best way for me? each url have one additional param (mySite.com/ssride360?site=SO) for example. Also I know that mySite.com/ssride360 would reference a folder in my project so wouldn't i be getting that file along with it (mySite.com/ssride360/Default6.aspx)?
At this point I think there are better ways then a url copy.
Suggestions?
Uri x = new Uri("http://www.mySite.com/ssride360");
Console.WriteLine (x.AbsolutePath);
prints /ssride360
This method will allow you to get the name even if there is something after it. It is also a good model to use if you plan on putting other stuff after the name and want to get those values.
char [] delim = new char[] {'/'};
string url = "www.mySite.com/ssride360";
string name = url.Split(delim)[1];
Then if you had a URL that included an ID after the name you could do:
char [] delim = new char[] {'/'};
string url = "www.mySite.com/ssride360/abc1234";
string name = url.Split(delim)[1];
string id = url.Split(delim)[2];
URL rewriting is a common solution for this problem. You give it the patterns of the URL's you want to match and what it needs to change it into. So it would detect www.mySite.com/ssride360 and transform it into www.mySite.com?name=ssride360. The user of the website sees the original URL and doesn't know anything changed, but your code sees the transformed URL so you can access the variables in the normal way. Another big plus is that the rules allow you to set the patterns that get transformed as well as the ones that just get passed through to actual folders / files.
http://learn.iis.net/page.aspx/461/creating-rewrite-rules-for-the-url-rewrite-module/
Like javascript? If so...
<script type="text/javascript">
function getName() {
var urlParts = window.location.pathname.split('/'); //split the URL.
return urlParts[1]; //get the value to the right of the '/'.
}
</script>

Categories

Resources