简体   繁体   中英

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.

Currently we run a bat as admin using installutil. It can be done also with sc create, from an administrator command prompt.

What is the easiest way to install a service from the windows form?

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?

You can use the following code to install a service:

Note: you will need to add a reference to 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 :

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"; enables the process to start under administrator privileges.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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