How can I set sort of “Start in”-path for a Windows Service

馋奶兔 提交于 2019-12-11 06:51:27

问题


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)
        });
    }

    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 :)


回答1:


You will need to read the folder location from a configuration file, or the registry. There's no analogue of starting directory.




回答2:


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.



来源:https://stackoverflow.com/questions/6544437/how-can-i-set-sort-of-start-in-path-for-a-windows-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!