从Windows表单应用程序

时间:2016-11-16 16:09:40

标签: c# winforms

我有一个按钮,允许用户浏览文件,然后将路径+文件名存储在变量中:

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

浏览.exe后,我想安装该服务。

目前我们使用installutil以管理员身份运行bat。也可以使用sc create从管理员命令提示符完成。

从Windows窗体安装服务的最简单方法是什么?

我可以创建一个字符串,如:

sc create "servicename" binpath="filepath"

从程序中运行它?

我想到的另一个选择是让程序创建一个bat并以管理员身份运行它?

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码安装服务:

注意:您需要添加对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);

答案 1 :(得分:0)

您可以使用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";使进程能够以管理员权限启动。