c# - Windows 服务启动失败 : Cannot start service from the command line or debugger

标签 c# windows-services

<分区>

嗨,我收到这个错误

Cannot start service from the command line or debugger. A winwows Service must first be installed(using installutil.exe) and then started with the ServerExplorer, Windows Services Afministrative tool or the NET START command.

我不明白为什么我会收到这个错误。 这是我的代码:

{
    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;
}

最佳答案

观看this video ,我有同样的问题。他还向您展示了如何调试该服务。

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

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

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

如果您处于 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
}

请记住,尽管这是调试服务的绝佳方式。它不会调用 OnStop() 除非您明确调用它类似于我们在 onDebug() 函数中调用 OnStart(null) 的方式.

关于c# - Windows 服务启动失败 : Cannot start service from the command line or debugger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11573724/

相关文章:

c# - WCF 服务库仅在从 Visual Studio 运行时有效

.net - 唤醒 Windows 服务中运行的 WCF 服务

debugging - 如何调试崩溃的 Windows 服务?

c# - 如何设置变量的属性

c# - Windows 服务给出错误 - System.Security.SecurityException

c - 使用winsvc.h中的SERVICE_TABLE_ENTRY避免编译器警告的正确类型转换是什么

c# - 如何让我的 Windows 服务以特定的时间间隔运行?

使用 LINQ 删除 C# 数据集列

c# - 即使用户启动模态对话框,如何使非模态对话框保持在顶部

c# - 消息队列循环