我有一个用C#编写的标准.NET Windows服务.

它能在不使用InstallUtil的情况下自行安装吗?

我希望能够调用以下内容:

MyService.exe -install

它将产生与调用相同的效果:

InstallUtil MyService.exe

推荐答案

是的,这是完全可能的(即我完全可以这样做);您只需要引用正确的DLL(System.ServiceProcess.dll)并添加一个安装程序类……

Here's an example:

[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
    public MyServiceInstallerProcess()
    {
        this.Account = ServiceAccount.NetworkService;
    }
}

[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
    public MyServiceInstaller()
    {
        this.Description = "Service Description";
        this.DisplayName = "Service Name";
        this.ServiceName = "ServiceName";
        this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
    }
}

static void Install(bool undo, string[] args)
{
    try
    {
        Console.WriteLine(undo ? "uninstalling" : "installing");
        using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
        {
            IDictionary state = new Hashtable();
            inst.UseNewContext = true;
            try
            {
                if (undo)
                {
                    inst.Uninstall(state);
                }
                else
                {
                    inst.Install(state);
                    inst.Commit(state);
                }
            }
            catch
            {
                try
                {
                    inst.Rollback(state);
                }
                catch { }
                throw;
            }
        }
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
    }
}

.net相关问答推荐

实体框架核心:Azure容器应用程序的执行超时已过期

.NET 7,8 System.Text.Json反序列化多态参数

为什么DotNet新的webapi;命令会为我生成不同的文件夹

.NET MAUI 的登录页面

如何在 C# 中将 HTTP 发布请求发送到另一个 API?

Dictionary.FirstOrDefault() 如何判断是否找到了结果

C#字符串的GetHashCode()是如何实现的?

是否可以模拟 .NET HttpWebResponse?

AutoMapper 的替代品

C# 时间跨度毫秒与 TotalMilliseconds

.NET 4.0 中有内置的二叉搜索树吗?

如何找到 ManualResetEvent 的状态?

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") 返回上午时间而不是下午时间?

迭代器和枚举器的区别

如何使用 Entity Framework Code First CTP 5 存储图像?

为什么 double.NaN 不等于自身?

使 HashSet 不区分大小写

如何访问 Session 变量并在 javascript 中设置它们?

MailMessage,Sender 和 From 属性的区别

C# 相当于 Java 的 Exception.printStackTrace()?