HttpRequest.Url.AbsolutePath vs HttpRequest.Path in .NET - c#

I've been using the HttpRequest class in some legacy code, and I've seen that sometimes the path part is obtained using HttpRequest.Path and some other times using HttpRequest.Uri.AbsolutePath.
I personally don't see any difference between both, but maybe I'm missing something.
Are the results of HttpRequest.Path and HttpRequest.Uri.AbsolutePath always 100% equivalent?

Looking at the Reference Source for the Uri, it is built using the Path, so they should be equivalent:
_url = BuildUrl(() => Path);

Yes. They are one and the same. I just run a couple of quick tests and found that the they both are the same. Some research over it showed me that, httprequest.path is an virtual path to the current request which should be exactly the same as absolute path of the URI from that request.

Yes, they should
http://msdn.microsoft.com/en-us/library/system.web.httprequest.path(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.uri.absolutepath(v=vs.110).aspx
The HttpRequest.Path returns an absolute path

Related

WebApi - How to include relative paths for included App_Data XML files?

Question Background:
I have a WebApi controller who's logic code relies on reading data contained in a number of XML files. These XML files have been included in the App_Data folder of the WebApi project.
The Issue:
I'm trying to use the relative path of the XML files in the following way:
[System.Web.Http.HttpGet]
public string CallerOne()
{
string docOne = #"~\AppData\DocOne.xml";
string poll = #"~\AppData\Poll.xml";
var response = _Caller.CallService(docOne, poll);
return ConvertXmlToJson(response);
}
When running the WebApi code and calling the Url to the CallerOne method I receive the following error:
An exception of type 'System.IO.DirectoryNotFoundException'
occurred in System.Xml.dll but was not handled in user code
Additional information: Could not find a part of the path
'C:\Program Files (x86)\IIS Express\~\AppData\FPS.xml'.
I also want to eventually publish this to Azure and include these files.
How can I use the relative path to read in the XML files in the App_Data folder?
Ended up finding the answer.
The following is needed to read the relative paths in a WebApi project:
var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(#"~/App_Data/yourXmlFile.xml");
As jdweng inferred several months back, Environment.GetEnvironmentVariable("AppData") would seem to be the preferred method. The OP's auto-accepted answer and that give quite different results. For example, using both of those in my project, I get:
C:\\Projects\\PlatypusReports\\PlatypusReports\\App_Data\\yourXmlFile.xml
...for the OP's long-winded code, namely this:
var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(#"~/App_Data/yourXmlFile.xml");
...and this:
C:\\Users\\cshannon\\AppData\\Roaming
...for jdweng's code, to wit:
string appData = Environment.GetEnvironmentVariable("AppData");
OTOH, this code:
string appDataFolder = HttpContext.Current.Server.MapPath("~/App_Data/");
returns:
C:\\Projects\\PlatypusReports\\PlatypusReports\App_Data\
So it's very similar in results (if not methodology) to the first example above. I actually got it from a question I asked almost two years ago, which I had forgotten about.
I'm not positive if jdweng's approach would work as expected once the app is deployed on a server, but I have much more confidence in it than the other approaches.
Can anyone verify?
UPDATE
The accepted answer here has 237 upvotes at time of typing, so seems pretty reliable, albeit 6 years old (42 in dog years, which may be a good sign).
Your approach is fine. You just had some tpying error,
You wrote
string docOne = #"~\AppData\DocOne.xml";
But it should have been
string docOne = #"~\App_Data\DocOne.xml";

Check if ASP.NET WebForms page exists based upon relative URL provided in Query String

Given a query string url of the form "~/folder/page.aspx", is there a way to check if that page exists within the scope of the application?
I'm in a situation where I'm fixing a minor bug where, if a user attempts to log in to the application from a set of publicly accessible application error pages, then they're redirected back to that public error page. I've been asked to have the user be redirected to the main home page if they're logging in to the application from this state.
So far I've fixed the issue by hard coding the paths to the affected pages in a switch statement, checking the querystring against the hardcoded paths. I feel this is hacky and bad, and would love a more dynamic solution, but I can't seem to find one.
Any help would be greatly appreciated.
Edit - Specifically, my preferred solution would simply be to check that the path defined by the query string url (without a priori knowledge of the exact format) leads to a specified folder within the scope of the application.
So, after looking some more, I discovered Server.MapPath. I can use this in conjunction with System.IO.Directory to see if the file is contained within the directory.
string targetUrl = Request.QueryString["redirect"];
string serverUrlPath = Server.MapPath(targetUrl);
string serverDirPath = Server.MapPath("~/ErrorPages");
foreach (string file in Directory.EnumerateFiles(serverDirPath))
{
if (file.Equals(serverUrlPath, StringComparison.OrdinalIgnoreCase))
{
Response.Redirect(Master.ProjectSearchRedirect());
}
}
Response.Redirect(targetUrl);
I was hoping for something a little more refined (even just a Directory.Contains kind of encapsulation).

Image path file not found

I have spent quite a while trying to solve this problem, but to no avail. I have searched stackoverflow as well as Google and have not been able to resolve my (seemingly) simple problem.
I am getting a FileNotFoundException in the following line:
Image.FromFile("\\Resources\\Icons\\key-icon.png");
The folders and image are really there, and I can't see what the problem is.
You should consider that it is started from "yourproject/bin/Release" so you need to go up 2 directories. Do this:
Image.FromFile("..\\..\\Resources\\Icons\\key-icon.png");
Try using an absolute path not a relative one... i.e.
Image.FromFile(Server.MapPath(#"~\Resources\Icons\key-icon.png"));
Image.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
#"Resources\\Icons\\key-icon.png"))
Base-directory Combine your file-name
You may be missing a leading ".":
Image.FromFile(".\\Resources\\Icons\\key-icon.png");
Internally, Image.FromFile uses File.Exists to check whether the file exists. This method returns false when:
the file does not exist (makes sense)
the current process identity does not have permission to read the file
It may be that the second option is your problem.
And another possibility: is Resources a network share? In that case you should use the following:
Image.FromFile("\\\\Resources\\Icons\\key-icon.png");
For this case I discovered that sikuli does not automatically detect the root folder of the project. What you should do for this case is specify the folder using the command System.getProperty("user.dir");
import org.sikuli.script.*;
public class Test {
public static void main(String[] args) {
Screen s = new Screen();
try{
String pathYourSystem = System.getProperty("user.dir") + "\\";
s.click(pathYourSystem + "imgs/spotlight.png");
//s.wait(pathYourSystem + "imgs/spotlight-input.png");
//s.click();
s.write("hello world#ENTER.");
}
catch(FindFailed e){
e.printStackTrace();
}
}
}

Starting another application from within C# code

How can I start another application from within C# code? I can't get this piece to work correctly
System.Diagnostics.Process.Start(#"%userprofile%\AppData\Local\Google\Application\chrome.exe");
Edit:
Wow I was dumb and just noticed what I forgot in the filepath. Thanks for the answers though they helped teach me some other useful things.
I don't think Process.Start expands environment variables for you. Try this:
var path = Environment.ExpandEnvironmentVariables(#"%userprofile%\AppData\Local\Google\Application\chrome.exe");
Process.Start(path);
try this link for starting external program
Also try this Similar Question on stackoverFlow
this is an example here
string winpath = Environment.GetEnvironmentVariable("windir");
string path = System.IO.Path.GetDirectoryName(
System.Windows.Forms.Application.ExecutablePath);
Process.Start(winpath + #"\Microsoft.NET\Framework\v1.0.3705\Installutil.exe",
path + "\\MyService.exe");
And in your case ,write the following on top where all the using namespaces are listed
using System.Diagnostics;
using System;
so then in your code directly write the above code...

get main part of url including virtual directory

I am working with .net 4.0 c#.
I want to be able to get the url from the current http request, including any virtual directory. So for example (request and sought value):
http://www.website.com/shop/test.aspx -> http://www.website.com/shop/
http://www.website.com/test.aspx -> http://www.website.com/
http://website.com/test.aspx -> http://website.com/
How is it possible to achieve this?
This is what I use
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath;
Request.Url should contain everything you need. At that point it's a matter of checking the string, and what you prefer to grab from it. I've used AbsoluteUri before, and it works.
This example isn't fool proof, but you should be able to figure out what you need from this:
string Uri = Request.Url.AbsoluteUri;
string Output = Uri.Substring(0, Uri.LastIndexOf('/') + 1 );
This solution could work and is shorter:
string url = (new Uri(Request.Url, ".")).OriginalString;
This should work
Request.Url.OriginalString.Substring(0, Request.Url.OriginalString.LastIndexOf(Request.FilePath.Substring(Request.FilePath.LastIndexOf("/")))) + "/"

Categories

Resources