convert path into absolute url - c#

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

Related

C# cut file Name from Path

I am creating an Image Extraction tool and I am able to retrieve the Images with full path..
For Example:
I need to cut the File name (rss) from path...
I search posts and Tried following
//1.
//string str = s.Split('/', '.')[1];
//2.
string s1;
// string fileName = "abc.123.txt";
int fileExtPos = s.LastIndexOf(".");
if (fileExtPos >= 0)
s1 = s.Substring(0, fileExtPos);
//3.
//var filenames = String.Join(
// ", ",
// Directory.GetFiles(#"c:\", "*.txt")
// .Select(filename =>
//4.
// Path.GetFileNameWithoutExtension(filename)));
None seems to be working
I want the name between "images" and "png" ..What can be the exact code?
Any Suggestion will be helpful
Just use the class Path and its method GetFileNameWithoutExtension
string file = Path.GetFileNameWithoutExtension(s);
Warning: In this context (just the filename without extension and no arguments passed after the URL) the method works well, however this is not the case if you use other methods of the class like GetDirectoryName. In that context the slashes are reversed into Windows-style backslashes "\" and this could be an error for other parts of your program
Another solution, probably more WEB oriented is through the class Uri
Uri u = new Uri(s);
string file = u.Segments.Last().Split('.')[0];
but I find this a lot less intuitive and more error prone.
In your example you're using a uri so you should use System.Uri
System.Uri uri = new System.Uri(s);
string path = uri.AbsolutePath;
string pathWithoutFilename = System.IO.Path.GetDirectoryName(path);
Why use Uri? Because it will handle things like
http://foo.com/bar/file.png#notthis.png
http://foo.com/bar/file.png?key=notthis.png
http://foo.com/bar/file.png#moo/notthis.png
http://foo.com/bar/file.png?key=moo/notthis.png
http://foo.com/bar/file%2epng
Etc.
Here's a fiddle
You should use the various System.IO.Path functions to manipulate paths as they work cross platform. Similarly you should use the System.Uri class to manipulate Uris as it will handle all the various kinds of edge cases like escaped characters, fragments, query strings, etc.

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

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

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.

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"

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