c# - 如何将参数传递给 Windows 服务?

标签 c# windows-services

我试图将参数传递给 Windows 服务。

这是我的代码片段:

class Program : ServiceBase
{
    public String UserName { get; set; }
    public String Password { get; set; }

    static void Main(string[] args)
    {
        ServiceBase.Run(new Program());
    }

    public Program()
    {
        this.ServiceName = "Create Users Service";
    }

    protected override void OnStart(string[] args)
    {
        base.OnStart(args);

        String User = UserName;
        String Pass = Password;
        try
        {
            DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");

            DirectoryEntry NewUser = AD.Children.Add(User, "user");
            NewUser.Invoke("SetPassword", new object[] { Pass });
            NewUser.Invoke("Put", new object[] { "Description", "Test User from .NET" });
            NewUser.CommitChanges();
            DirectoryEntry grp;
            grp = AD.Children.Find("Administrators", "group");
            if (grp != null)
            {
                grp.Invoke("Add", new object[] { NewUser.Path.ToString() });
            }
            Console.WriteLine("Account Created Successfully");
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.ReadLine();
        } 
    }

如何将用户名和密码传递给此 Windows 服务?

最佳答案

你可以像这样在启动时传递参数:

  1. 右键单击“我的电脑”并选择“管理”->“服务和应用程序”->“服务”
  2. 右键单击您的服务,选择“属性”,然后您应该会在“常规”选项卡下看到“启动参数”框。

如果您在那里输入例如 User Password,您将在 protected override void OnStart(string[] args) 中获得这些参数作为 args。 然后像这样使用它:

protected override void OnStart(string[] args)
{
    base.OnStart(args);
    UserName = args[0];
    Password = args[1];
    //do everything else
}

关于c# - 如何将参数传递给 Windows 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6490979/

相关文章:

c# - MySQL 连接器打开连接时超时

c# - Windows 服务仅运行列出的第一个服务

c# - 在 Web 应用程序中管理长时间运行的进程的策略?

c# - SQL 用户定义的聚合值保留顺序?

c# - 良好的 C#.NET 解决方案来管理频繁的数据库轮询

c# - .Net/C# 是否有工具来捕获类之间的*运行时*依赖关系?

.net - 用于缓存的 AppFabric

c# - Expression.Constant(value, type) 类型未知。如何定义类型

msbuild - 使用 MSBuild 和 Microsoft.Sdc.Tasks 安装 win32 服务

f# - 安装 Windows 服务时出错(在 F# 中)