I have following class, which is used by a Windows Installer project, to install a service:
[RunInstaller(true)]
public sealed class Installer : System.Configuration.Install.Installer
{
private readonly string _installDir;
public Installer()
{
var locatedAssembly = this.GetType().Assembly.Location;
this._installDir = Path.GetDirectoryName(locatedAssembly);
var serviceProcessInstaller = new ServiceProcessInstaller
{
Account = ServiceAccount.LocalSystem
};
var serviceInstaller = new ServiceInstaller
{
ServiceName = Settings.Service.Name,
StartType = ServiceStartMode.Automatic
};
this.Installers.Add(serviceProcessInstaller);
this.Installers.Add(serviceInstaller);
this.Context = new InstallContext(this._installDir + @"\install.log", new[]
{
string.Format("/assemlypath={0}", locatedAssembly)
});
开发者_Go百科}
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
var serviceController = new ServiceController(Settings.Service.Name);
serviceController.Start();
serviceController.WaitForStatus(ServiceControllerStatus.Running);
}
}
If we call the following code inside a console application, the directory of the assembly will be taken:
using (var stream = File.Open("foo.store", FileMode.OpenOrCreate))
If I run the line from my Windows Service, C:\Windows\System32\
will be taken instead.
How can I change this behaviour?
For clarification: I do not want to utilize any assembly-spying (get the path of the assembly from this.GetType()
...) or anything in the appsettings. I want it to work straight without any magic on the caller side :)
Don't trust the current directory. If the file is located besides the service use:
string sdir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
to recover the path in which the executable is, and use it as a base path to look for the file.
You will need to read the folder location from a configuration file, or the registry. There's no analogue of starting directory.
精彩评论