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

问题描述 投票:0回答:6

嗨,我收到此错误

无法从命令行或调试器启动服务。必须首先安装 winwows 服务(使用 installutil.exe),然后使用 ServerExplorer、Windows Services Afministrative 工具或 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;
}
c# windows-services
6个回答
132
投票

观看这个视频,我也有同样的问题。他还向您展示了如何调试该服务。

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

您将其添加到

Service1.cs
文件中:

public void onDebug()
{
    OnStart(null);
}

如果您处于 DEBUG Active Solution 配置中,则可以更改 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
}

请记住,虽然这是调试服务的好方法。它不会调用

OnStop()
,除非您明确地调用它,类似于我们在
OnStart(null)
函数中调用
onDebug()
的方式。


39
投票

手动安装您的服务

要手动安装或卸载 Windows 服务(使用 .NET Framework 创建),请使用实用程序

InstallUtil.exe
。该工具可以在以下路径中找到(使用适当的框架版本号)。

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

安装

installutil yourproject.exe

卸载

installutil /u yourproject.exe

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

以编程方式安装服务

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


1
投票

您的代码与服务安装无关,这不是问题。

为了测试该服务,您必须按照指示安装它。

有关安装服务的更多信息:安装和卸载服务


0
投票

我会建议创建一个安装项目,因为部署这似乎是最方便的,没有手动复制文件的麻烦。 按照 Windows 服务设置创建教程,您就知道如何创建它。此实例适用于 vb.net,但对于任何类型都是相同的。


0
投票

要安装 Open CMD,并在安装后输入

{YourServiceName} -i
,然后输入
NET START {YourserviceName}
来启动服务

卸载

要卸载打开CMD并输入

NET STOP {YourserviceName}
,一旦停止,输入
{YourServiceName} -u
,它应该被卸载


0
投票

转到应用程序.config

寻找

<setting name="RunAsWindowsService" serializeAs="String">
    <value>True</value>
  </setting>

设置为假

© www.soinside.com 2019 - 2024. All rights reserved.