Windows服务启动失败:无法从命令行或调试器启动服务

pax*_*cow 52 c# windows-services

嗨,我收到这个错误

无法从命令行或调试器启动服务.首先必须安装winwows服务(使用installutil.exe),然后使用ServerExplorer,Windows Services管理工具或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;
}
Run Code Online (Sandbox Code Playgroud)

Ces*_*sar 72

观看此视频,我有同样的问题.他向您展示了如何调试服务.

以下是在Visual Studio 2010/2012中使用基本C#Windows服务模板的说明.

您将其添加到Service1.cs文件:

public void onDebug()
{
    OnStart(null);
}
Run Code Online (Sandbox Code Playgroud)

如果您在DEBUG Active Solution Configuration中,则更改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
}
Run Code Online (Sandbox Code Playgroud)

请记住,虽然这是调试服务的一种很棒的方法.它不会调用,OnStop()除非你明确地调用它类似于我们OnStart(null)onDebug()函数中调用的方式.


Ria*_*Ria 30

手动安装服务

要手动安装或卸载Windows服务(使用.NET Framework创建),请使用实用程序InstallUtil.exe.可以在以下路径中找到此工具(使用适当的框架版本号).

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe

安装

installutil yourproject.exe
Run Code Online (Sandbox Code Playgroud)

要卸载

installutil /u yourproject.exe
Run Code Online (Sandbox Code Playgroud)

请参阅:如何:安装和卸载服务 (msdn)

以编程方式安装服务

要使用C#以编程方式安装服务,请参阅以下类ServiceInstaller (c-sharpcorner).

  • 运行`installutil`之后它说它成功了,但我仍然无法启动服务或在服务管理器中看到它 (6认同)
  • 我发誓,我在野外找到的每个 MSDN 链接都已损坏。ms docs 是为什么在答案中包含相关信息很重要的典型代表。(你在这方面做得很好!谢谢!) (2认同)