file path using C# - c#

I have a windows service which is using a method from a class library with same asp.net solution. in class library, I have a method with following line:
reader = XmlReader.Create(HttpContext.Current.Server.MapPath("~/TestDevice/Data.xml"), settings);
When control comes to this line. I get exception. I tried to debug the code and found that when service tries to access this method then HttpContext.Current.Server is null. What is alternative syntax.
I tried to access this class library method from web application and it works fine.
System.IO.Path.GetFullPath("/TestDevice/Data.xml") returns C:\\TestDevice\\Data.xml instead of the actual directory path
I want to get full path of the folder.
Please suggest solution.

http://msdn.microsoft.com/en-us/library/aa457089.aspx
string path;
path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );

You will need a configuration file that can have the "root" directory set specifically. This will allow the windows service to know what directory to place files into regardless of where its executable sits and regardless of where the asp.net site is configured to run.

I don't think the ~ will work in this case, you will need to provide a relative path. Something like "../../TestDevice/Data.xml" should work.

Related

How to obtain the current executing directory irrespective of the host type

I have a code snippet that loads some assemblies from the current executing directory at runtime.
The code is part of a library that can be hosted in a console app/windows service/aspnet web app etc.
Is there a single API call that will provide the current directory the code is running from?
For a console/windows service AppDomain.CurrentDomain.BaseDirectory; returns the correct
path but the same call in an ASPNET app returns the path to the virtual root instead of the path
to the [virtualroot]\bin directory of the web app.
For ASPNET AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; returns what I want.
I could make a check like the following so that I get the correct path irrespective of the host:
string path = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath ??
AppDomain.CurrentDomain.BaseDirectory;
This sort of heuristic seems a bit hackish and I was hoping there is a single API call that will provide the expected results
To check where the current assebly is stored you can use this:
Assembly.GetExecutingAssembly().CodeBase
Or if your code is in a library and you wand the location of the started exe you can use GetEntryAssembly().
The codeBase is in URI syntax. To get the path (if required) you can use:
var path = new Uri(codeBase).AbsolutePath;

ASP physical and virtual path

This is the first time I make an asp site. This line of code is working fine on my pc but obviously to make it working on the production server I need to change the reference.
DirectoryInfo dir = new DirectoryInfo(#"C:\Users\Pink\Documents\Visual Studio 2012\Projects\ManagDoc_Framework\Test1_managDoc\Test1_managDoc\Allegati\" + recordIDcreateDir);
I have tried many sort of path combination but I am not getting it right.
I would like to find a solution that makes the code working on both pc, during development, and hosting server without having to change the code.
How should i write the path? Some help will be appreciated.
Use Server.MapPath method :
The MapPath method maps the specified relative or virtual path to the
corresponding physical directory on the server.
Additional details on W3schools.com, tutorial I followed, and where I learnt the existence of the above method.

How to map a windows service program's file

I am working on a windows service c# program.
I need to use a file. Here is my code
const string mail_file_path = #"template\mailbody.html";
But according to my log, there is an error like this:
Error: Could not find a part of the path 'C:\Windows\system32\template\mailbody.html'.
I use the app.configuration to use another file
<add key="TimeStampFilePath" value="timestamp.ini" />
StreamReader sr = new StreamReader(ConfigurationManager.AppSettings["TimeStampFilePath"]);
But I can't read the file.
When I run this project as a simple windows console project, it works. But after I run it using windows service mode, the two problems appear.
You could try:
// dir is path where your service EXE is running
string dir = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location);
// mail_file_path is where you need to search
string mail_file_path = Path.Combine(dir , #"\template\mailbody.html");
Take my answer as an integration to #CharithJ's post, which is definitely correct!!
If you have got template\mailbody.html in the same directory where the service exe resides. Try something like below and see. You could find the folder where the windows service .exe resides.
string mail_file_path = System.Reflection.Assembly.GetEntryAssembly().Location +
"\template\mailbody.html";
Or this also can help AppDomain.CurrentDomain.BaseDirectory
I found a way to solve the problem, thanks to the suggestion from #Macro. I get the windows service mapping directory using REGISTER API, then setting the working directory the same with it. Then I can use the relative path to get the file I need.

Server Root and MapPath()

I have a file structure set up like this:
ServerRoot
applicationRoot
filePage.aspx
files
chart.png
My application page called filePage.aspx uses another app to custom build charts. I need them saved in files folder. This is how our client's production server is set up and I cannot change this.
I do a _page.Server.MapPath("/files") but it gives me a InvalidOperationException and states Failed to map the path '/files'.
UPDATE:
So it has to be set up this way MapPath("/"). My local asp.net server can't handle the MapPath that way, but our IIS development box has no problem with it and it works fine. Interesting.
How do I get it to save to files?
I believe it's a security violation to go outside the directory structure of the virtual directory in asp.net 2.0 and up. You'll need to make a virtual directory to the directory and use that.
Use
Server.MapPath("~/files")
The ~ represents the root of the web application so the folder returned will be correct no matter which subdirectory you are in.
Try
_page.Server.MapPath("files")
_page.Server.MapPath() will attempt to map from the root of the application (NOT the root of the server).
Try _page.Server.MapPath("../files").
EDIT
You may run into security issues when trying to map outside of your application root. If that is the case, you can do something like this:
Server.MapPath("~").Substring(0, Server.MapPath("~").IndexOf(VirtualPathUtility.ToAbsolute("~").Replace("/", "\"))) + "\files"
This looks rather complex, but essentially says "map my application, then remove the application root from the end and add '\files' instead".

Ubiquitous way to get the root directory an application is running in via C#

My application requires that I have access to the file system. Regardless if the code runs on a web server or a console app, how can I get the root directory the application is running in. Something like C:\TheApplication...
Thanks!
Easiest is probably:
System.Reflection.Assembly.GetExecutingAssembly().Location
Hope this helps,
-Oisin
You can try this:
String path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
You can read more about the two classes here:
Assembly class
Path class
I just tested out a very basic way to do this that works in both asp.net and within a windows service.
var binariesPath = string.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath)
? AppDomain.CurrentDomain.BaseDirectory // Windows Service
: AppDomain.CurrentDomain.RelativeSearchPath; // Asp.net
Even easier:
string myPath = Application.ExecutablePath;
For winforms application, this is always set.

Categories