[英]Install service from windows form application
我有一個按鈕,允許用戶瀏覽文件,然后將路徑 + 文件名存儲在變量中:
openFileDialog1.ShowDialog();
string filePath = openFileDialog1.FileName;
瀏覽 .exe 后,我想安裝該服務。
目前我們使用 installutil 以管理員身份運行 bat。 也可以從管理員命令提示符使用 sc create 來完成。
從 Windows 窗體安裝服務的最簡單方法是什么?
我可以創建一個字符串,如:
sc create "servicename" binpath="filepath"
並從程序中運行它?
我正在考慮的另一個選擇是讓程序創建一個 bat 並以管理員身份運行它?
您可以使用以下代碼安裝服務:
注意:您需要添加對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;
}
你只需要像這樣稱呼它:
Assembly assembly = Assembly.LoadFrom(filePath);
InstallService("name", assembly);
您可以使用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();
行startInfo.Verb = "runas";
使進程能夠在管理員權限下啟動。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.