IIS/HttpHandler: Get relative absolute path? - c#

I've got a site setup in IIS to run at http://localhost/WebApplication6. In my web application I have a handler (implements IHttpHandler). When I print context.Request.Url.AbsolutePath, I get /WebApplication6/whaetever. I want to trim off /WebApplication6 (the local site name). How can I do that? Is there a way to get the "WebApplication6" bit so I know what to trim off? (inside IHttpHandler.ProcessRequest).

Your best bet would be HttpRequest.AppRelativeCurrentExecutionFilePath - it provides path relative to your web application root directory. However, it will be in form of "~/whatever" where ~/ indicates app relative path. If your requirement is to get /whatever then you can strip off ~ using string functions.
BTW, here's good article that will help you make sense of all paths: http://www.west-wind.com/weblog/posts/132081.aspx

VirtualPathUtility.GetDirectory(context.Request.Url.AbsolutePath)

Related

Virtual Path Problems

I am currently trying to create multiple Applications within a single IIS-Website automatically.
Each application represents a Feature-Branch of a developer/feature.
The problem is, that the legacy application is not really made for running in a path that is not on the root. So the path the application thinks (and must think) it is running in, must be '/'.
It would come with re-structuring and re-testing pretty much everything related to urls, to change this. So for now, its not an option.
What i currently have:
[Features (Site)]
- [Feature_A (App)]
- [Feature_B (App)]
This results in Feature A being available under http://server/Feature_A and Feature B respectively.
Now when the Request reaches the application, the application must think that the url in which it was called is "http://server/" (or the Path being "/").
Chosing the correct app was achieved with the IIS URL-Rewrite module, and works quite well.
I use a cookie to decide which app to call, and the original '/' is rewritten to '/Feature_A/'
But now, when trying to eliminate the "/Feature_A" part of the Path within the app seems to be quite impossible.
Application.Context.RewritePath(newPath); // throws exeption -> different application
didnt really work out, because the new Path '/' points to a different application, and RewritePath doesnt like that.
Is there any way within the app or even in IIS to make the app think it is running on the root path?
Thank you in advance.

How to pass relative path to use the File.Delete static function in C#?

I've been trying to create a way to upload, download and delete a PDF file. The upload and the download function work fine, but when I try to delete the PDF it doesn't really work as I want it to.
It does work when I use this form:
File.Delete(#"C:\Users\Donovan\1_Test.pdf");
But it doesn't work when I try this:
File.Delete(#"~\1_Test.pdf");
I want to find a way to make the second line of code work, because I work in a team and we don't share the same file path.
Use Environment.GetFolderPath to find the user's home directory.
string home = Environment.GetFolderPath(Environment.SpecialFolder.UseProfile);
File.Delete(Path.Combine(home, "1_Test.pdf"));
You might also want to consider putting the file in the folder for temporary files instead. You can find that location with Path.GetTempPath. (Note that windows will not automatically clean up temporary files, so you still need to delete anything you put there after you are done with it.)
Try this. I think it works :D
File.Delete(Server.MapPath("~/") + "1_Test.pdf");
If you are all using the userpath you can go with this approach:
System.IO.File.Delete(
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
"1_Test.pdf"
)
);
You unfortunately cannot make it work with ~. This only works as a relative path for web applications.
We use a local config file for our application where each developer stores its own preferences and can change these independent of other developers.
Depending on your application (web, desktop, mobile, windows, linux, whatever) you can write a config-object and fill it or use i.e. appsettings in web.config for this purpose.
var basePath = Config.FileBase;
File.Delete(Path.Combine(basePath, "\1_Test.pdf"));
Another method:
File.Delete(Environment.ExpandEnvironmentVariables("%USERPROFILE%\\1_Test.pdf"));
Have you considered it to put the *.pdf files in a database?

Get FilePath for my excel file with sheetname

I am trying to do is to get filepath for my excel file. But I am unable to do so.
File is in Document/Visual Studio 2013/Project/ProjectName/a.xlsx
string path = Path.Combine(HttpContext.Current.Server.MapPath("~/"),"a.xlsx");
string SheetName="Sheet1";
Is it wrong way to do it or is it correct way?
This is the better answer according to me.
Better to save in
C:\Users\AJ1110\Documents\Visual Studio 2013\Projects\Proj\Proj
And in
program.cs
string pathfile = #"..\..\a.xlsx";
string sheetName = "Whatever_SheetName_IS!!!";
This might solve your problem.
HttpContext.Current does not work outside of a web context.
If your project is running inside a console or windows program, it cannot work with HttpContext.Current. MapPath is meant to translate a web path to a file system path. ~/ is a .Net convention for pointing the root web path of a web application.
You should explicit what are your requirements about how to resolve the folder containing your file.
Maybe should you simply put that in some configuration file (using settings property tab of the project by example) and retrieve it from there.
Edit:
So, from your comment on this question, it looks like you have to seek the xl file in the executing folder.
There is a number of ways for achieving this, depending on your application use cases.
By example, check this question.
Since your project is not a Web one, I expect that you some sort of Output where build process generates an executable file, some assemblies etc. You can put Build action of your Excel as Content (more details here) and use this base path to retrieve it:
System.Reflection.Assembly.GetExecutingAssembly().Location
It is important to think in terms relative to your executable (or executing assembly to be more precise), since your output will have to run outside your development environment and your excel must still be accessible.
Also, getting the exact executing assembly might be tricky in some scenarios.

Different slashes in web application paths

Why if I need to check if a folder exists on the web server I need to use backslashes in the path string:
if (Directory.Exists(#"~\assets\images\gallery\thumbnails"))
while to load the image I need to use slashes?
new WebImage("~/assets/images/gallery/thumbnail/name.jpg")
What's rule behind this?
Thanks.
Directory.Exists is a check against file system, which on Windows follows Windows path specification (the link is not exactly "specification," but will do for the purpose) which has \ as directory separator. On *nix systems, however, it would take / as directory separator. Thus, one should use Path.DirectorySeparatorChar for correctness and interoperability.
WebImage takes a URL reference (~ notwithstanding) and follows RFC 1738 which defines / as segment separator.
The two, while appearing similar, are different and (mostly) unrelated concepts.
For URLs you use forward slashes. In file paths in Windows you use backslashes. The first path is to a location on the hard drive. The second path is to a URL.
I believe WebImage refers to a virtual path, as used in URLs and referred to by the browser (for example).
Directory refers to actual physical directories on the server.
Windows uses backslash for physical directories.
URL conventions use slash for virtual paths.

Using HttpContext.Current.Server.MapPath in Window Application?

Can i do something like this in window Application?
HttpContext.Current.Server.MapPath("Email/ForgotPassword.txt"));
This project is a web based application.
And my next project is basically a window service...
Seeking for advice.
To get the path that the Exe is running at (which is a good location to add paths like "Email"), use:
string filePath = Application.StartupPath + "\\Email\\ForgotPassword.txt";
This path is the ..\bin\debug\Email path when you run it on VS and ..\Email path when you run it after installation.
There are few alternates to do this like these to access the directory path:
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
or
using System.IO;
using System.Reflection;
string path = Path.GetDirectoryName(
Assembly.GetAssembly(typeof(MyClass)).CodeBase);
you can do manipulation with the Path class like get the full path, directory name etc etc..
Check this MSDN forum thread How to get the current directory path c# winfows for application for details.
As you expecting to do windows application as like web.. It is not
possible.
If you're not processing requests from ASP.NET (or more specifically, System.Web), HttpContext.Current will be null. So then the answer is: no, you can't do what you are asking. Perhaps:
Assembly.GetExecutingAssembly().Location
combined with methods from Path would be useful?
As other people suggested it is not possible to lift up an entirelly new HttpContex out of nothing in Windows Application. The reason is that while some of the things you can obtain, others are based on the fact that you are running in web environment (for example - what would you put in the Request / Response properties of the .Current context?).
Anyway there are some things you can do as
Enumerate the IIS Web Sites / Virtual Directories, and find yours (sorry for the bad article code).
Then you can obtain the directory for the website, or even
Open website's Web.Config and read it (sorry for the bad code again).
Basically you are looking at the DirectoryEntry, WebConfigurationFileMap and VirtualDirectoryMapping classes although I am not quite sure where will you end up.
Still I will really ask you to review your architecture / question. It may be wrong from the start after you need the HttpContext in Windows application.
Maybe if you give us a bit more details we can help?
As mentioned by other HttpContex is not meant to be used in Window Application it is made for web application.
to simulate the HttpContext behavior in Window application you can declare global variable to use it in Application later.
also for current directory you can use Assembly.GetExecutingAssembly().Location

Categories

Resources