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

我试图将参数传递给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(); } } 

如何将UserName和Password传递给此Windows服务?

您可以在启动时传递参数,如下所示:

  1. 右键单击MyComputer,然后选择管理 – >服务和应用程序 – >服务
  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 } 

您将不得不从外部源加载这些值。 最简单的方法是使用Configuration Manager直接从app.config文件加载它们。 像这样的东西: http : //msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx

您可以使用配置文件注册表或任何类型的数据库

使用Environment.GetCommandLineArgs()

在运行时将参数(不使用注册表,文件或数据库)传递给Windows服务的两种最简单的方法是使用命名管道或在Windows中设置WCF服务,客户端调用该服务。 默认情况下,Windows服务是一个运行的重复过程。

如果您使用WCF,请在“添加删除程序”(或Windows 7的“程序和function”)中将其启用。

命名管道:

https://msdn.microsoft.com/en-us/library/aa365590(v=vs.85).aspx