简体   繁体   English

从 Windows 窗体应用程序安装服务

[英]Install service from windows form application

I have a button that allows the user to browse a file and then stores the path + filename in a variable:我有一个按钮,允许用户浏览文件,然后将路径 + 文件名存储在变量中:

openFileDialog1.ShowDialog();
string filePath = openFileDialog1.FileName;

After browsing for the .exe, I want to install the service.浏览 .exe 后,我想安装该服务。

Currently we run a bat as admin using installutil.目前我们使用 installutil 以管理员身份运行 bat。 It can be done also with sc create, from an administrator command prompt.也可以从管理员命令提示符使用 sc create 来完成。

What is the easiest way to install a service from the windows form?从 Windows 窗体安装服务的最简单方法是什么?

Can I create a string like:我可以创建一个字符串,如:

sc create "servicename" binpath="filepath"

and run it from the program?并从程序中运行它?

The other option I was thinking about was to make the program create a bat and run it as admin?我正在考虑的另一个选择是让程序创建一个 bat 并以管理员身份运行它?

You can use the following code to install a service:您可以使用以下代码安装服务:

Note: you will need to add a reference to System.ServiceProcess注意:您需要添加对System.ServiceProcess的引用

public static void InstallService(string serviceName, Assembly assembly)
{
    if (IsServiceInstalled(serviceName))
    {
        return;
    }

    using (AssemblyInstaller installer = GetInstaller(assembly))
    {
        IDictionary state = new Hashtable();
        try
        {
            installer.Install(state);
            installer.Commit(state);
        }
        catch
        {
            try
            {
                installer.Rollback(state);
            }
            catch { }
            throw;
        }
    }
}

public static bool IsServiceInstalled(string serviceName)
{
    using (ServiceController controller = new ServiceController(serviceName))
    {
        try
        {
            ServiceControllerStatus status = controller.Status;
        }
        catch
        {
            return false;
        }

        return true;
    }
}

private static AssemblyInstaller GetInstaller(Assembly assembly)
{
    AssemblyInstaller installer = new AssemblyInstaller(assembly, null);
    installer.UseNewContext = true;

    return installer;
}

You just need to call it like:你只需要像这样称呼它:

Assembly assembly = Assembly.LoadFrom(filePath);
InstallService("name", assembly);

You can use Process.Start :您可以使用Process.Start

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.Arguments = String.Format(@"sc create \"servicename\" \"{0}\"", filepath);
startInfo.Verb = "runas";
process.StartInfo = startInfo;
process.Start();

The line startInfo.Verb = "runas";startInfo.Verb = "runas"; enables the process to start under administrator privileges.使进程能够在管理员权限下启动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM