【问题标题】:Install service from windows form application从 Windows 窗体应用程序安装服务
【发布时间】:2016-11-16 16:09:40
【问题描述】:

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

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

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

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

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

我可以创建如下字符串吗:

sc create "servicename" binpath="filepath"

并从程序中运行它?

我正在考虑的另一个选择是让程序创建一个蝙蝠并以管理员身份运行它?

【问题讨论】:

标签: c# winforms


【解决方案1】:

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

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

【讨论】:

  • 我让它工作了。出现以下错误。 'Configs.exe 中发生'System.InvalidOperationException' 类型的未处理异常'
  • @TiraULTI 应用程序是否以管理员身份运行?
  • 以管理员身份运行是指以管理员身份打开它吗?如果是这样,那么是的
  • 我假设您尝试安装的应用程序在其中某处实现了ServiceBaseInstaller?即它是一项服务
  • 我要安装的应用程序是 Windows 服务。它不是我编写的,是我们团队的另一部分编写的。
【解决方案2】:

你可以使用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"; 行允许进程以管理员权限启动。

【讨论】:

  • 你确定这部分吗? String.Format(@"sc create \"servicename\" \"{0}\"", filepath);我不明白你把名字放在哪里了。
  • @TiraULTI 好吧,这就是您传递来安装服务的命令,所以在那里使用您想要的任何内容,例如在您所说的问题中 sc create "servicename" binpath="filepath" 所以您可以将其传递为 startInfo.Arguments,显然与正确的服务名称和文件路径集。
  • startInfo.Arguments = String.Format(@"sc create 'name12' binpath='"+filePath+"'"); 现在正在编译,当我搜索exe并选择它时,它唯一要做的就是打开cmd。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多