Reputation: 199
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?
Upvotes: 3
Views: 2703
Reputation: 6744
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.
Upvotes: 0
Reputation: 6744
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);
Upvotes: 3