Windows服务启动失败:无法从命令行或debugging器启动服务
嗨,我得到这个错误
无法从命令行或debugging器启动服务。 首先必须安装winwows服务(使用installutil.exe),然后使用ServerExplorer,Windows服务pipe理工具或NET START命令启动。
我不明白为什么会发生这个错误。 这是我的代码:
{ string Hash = ""; string connectionstring = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; SqlConnection myConnection = new SqlConnection(connectionstring); SqlCommand myCommand = new SqlCommand("GetNullHash", myConnection); myCommand.CommandType = CommandType.StoredProcedure; myConnection.Open(); SqlDataReader rdr = myCommand.ExecuteReader(); while (rdr.Read()) { string filename = @"\\" + rdr.GetString(3); filename = System.IO.Path.Combine(filename, rdr.GetString(2)); filename = System.IO.Path.Combine(filename, rdr.GetString(1)); Hash = rdr.GetString(0); Hash = computeHash(filename); } myConnection.Close(); return Hash; } 观看这个video ,我有同样的问题。 他向你展示了如何debugging服务。
以下是他在Visual Studio 2010/2012中使用基本C#Windows服务模板的说明。
您将此添加到Service1.cs文件中:
 public void onDebug() { OnStart(null); } 
如果您在debugging活动解决schemeconfiguration中,则更改Main()以这种方式调用您的服务。
 static void Main() { #if DEBUG //While debugging this section is used. Service1 myService = new Service1(); myService.onDebug(); System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); #else //In Release this section is used. This is the "normal" way. ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); #endif } 
 请记住,虽然这是一个很好的方式来debugging您的服务。 它不调用OnStop()除非你明确地调用它,类似于我们在onDebug()函数中调用OnStart(null)的方式。 
手动安装您的服务
 要手动安装或卸载Windows服务(使用.NET Framework创build),请使用实用程序InstallUtil.exe 。 该工具可以在以下path中find(使用适当的框架版本号)。 
 C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe 
安装
 installutil yourproject.exe 
卸载
 installutil /u yourproject.exe 
请参阅: 如何:安装和卸载服务 (msdn)
以编程方式安装服务
要使用C#编程安装服务,请参阅以下ServiceInstaller类(c-sharpcorner) 。
你的代码与服务安装无关,这不是问题。
为了testing服务,您必须按照指示进行安装。
有关安装服务的更多信息: 安装和卸载服务
我会build议创build一个安装项目的原因,同时部署这似乎是最好的方便,没有手动复制文件的头痛。 按照Windows服务设置创build教程 ,你知道如何创build它。 而这个实例是用于vb.net的,但是对于任何types都是一样的。
 要安装Open CMD,并在NET START {YourserviceName}input一次其安装types的{YourServiceName} -i以启动您的服务 
卸载
 要卸载Open CMD并键入NET STOP {YourserviceName}一旦停止input{YourServiceName} -u ,应该卸载它 
转到App.config
找
 <setting name="RunAsWindowsService" serializeAs="String"> <value>True</value> </setting> 
设置为False