How to map a windows service program's file - c#

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.

Related

Run exe from its folder

this is my scenario: I have an executable file that convert html files to pdf.
This exe work only if you start it from its folder.
Example: the exe is in C:\HtmlToPdf, so, in the prompt I will do this:
C:\> cd HtmlToPdf
C:\HtmlToPdf> htmltopdf.exe htmlFile pdfFile
So, there is a way to do this in c#? Because I tried this:
FileInfo htmlInfo = new FileInfo(executablePath + #"\" + filename);
var procInfo = new ProcessStartInfo("wkhtmltopdf.exe",htmlInfo.FullName + " " + htmlInfo.FullName.Replace(".html",".pdf"));
procInfo.WorkingDirectory=executablePath;
procInfo.UseShellExecute = false;
Process.Start(procInfo);
But it doesn't work.
wkhtmltopdf's documentation/wiki states that it will struggle to find a file if you use its full path. You need to append file:/// to the beginning of the file name
Note that on Windows, you can't use absolute path names with drives for HTML files at the moment:
wkhtmltopdf d:\temp\x.html x.pdf
will fail. You need to rather use file:/// URLs:
wkhtmltopdf file:///d:/tmp/x.html x.pdf
This answer may help in the appending
From where you are calling the EXE .. .whether its Windows Form application or Webforms....
If its windows forms it will work
else
if its Webforms like asp.net you have to change the properties of IIS Server to start the exe
Because due to some security reasons microsoft will not allow you to start the process class from IIS server... but the same code will work from Visualstudio ..
Here is my code
To get Current Exe Executable path
string sCurrentPAth = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Process.Start(#"E:\Debug\MyExe.exe", "arg1 arg2 arg3");
Its Working Correctly .....

file path using 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.

Writing to a file I get unauthorized access error.How can I do it?

Despite numerous post on the web I cannot find an answer to my problem.
I am writing an application that writes csv files to folders.Users should be able to pick a directory.
I am developing in windows 7 using vs2010 running my app in Admin Mode.Regardless of all this I still get the "Unauthorized access exception" when I do
var path=#"c:\" or c:\MyFolder
StringBuilder sb=new StringBuilder();
sb.AppendLine("Test");
var myFile=sb.ToString();
using (var writer=new StreamWriter(path))
{
writer.Write(myFile);
}
Am I missing something?
I have feeling that in window7 you can only write to designated folders.Is this what's happening?
any suggestions?
EDITED
I have created few folders under "C:\MyFolder\"
I am not using any credentials eg windows impersonation etc..
It does write if it writes to the bin\debug\ of my class library. but not to any designated folder.
Is your code snippet the real code causing the problem?
On the face of it, you are trying to stream the text "Test" into a directory on the file system, not trying to write a file. (path is just assigned to #"C:\"). I'm not surprised that you get an UnauthorizedAccessException.
Assign the full path of the file you want to write into your path variable, and I imagine you'll succeed.
Try running your app with "Run as Administrator". The comments above will probably also steer you in the right direction. You should definitely pick a directory that your windows users has access to edit.

C# How to find WCF IIS deployment/virtual directory at runtime to change name of log file?

I am trying to change the name of a c# WCF logfile based on the name of the IIS Virtual directory it is deployed to.
I tried to use the Directory.GetCurrentDirectory() call but it returns the directory c:\windows\system32\inetsrv regardless which virtual directory the WCF apps was deployed to..
So should I be looking into the VirtualDirectory Class ?? Any sample code on how to find the current Virtual Directory ?
Thanks !
Did you try this:
string path = HostingEnvironment.MapPath("~");
HostingEnvironment.ApplicationPhysicalPath
gives you the same thing as the accepted answer (in a more direct way).

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