Debug Windows Service

后端 未结 11 1410
既然无缘
既然无缘 2020-11-29 17:09

Scenario

I\'ve got a windows service written in C#. I\'ve read all the google threads on how to debug it, but I still can\'t get it to work. I\'ve run \"PathTo.Net

11条回答
  •  旧巷少年郎
    2020-11-29 18:06

    It can be that service name is not what you expect and that's why you can't find it. Service name is defined in ServiceInstaller properties in .NET project and does not have to correspond with executable name in any way. But if you're sure the service is not listed after installation, here is what you can do.

    First, service installation. There are 2 methods, InstallUtil.exe and SC.exe. First one is tailored specifically for .NET services as it will run all ProjectInstaller and ServiceInstaller code. Second one will not do that but it will give you more options and is usually more effective i.e. likely to succeed where InstallUtil fails. This can be when there is an exception in any installer code.

    You've already tried installing with InstallUtil so here is SC version:

    sc create MyService binPath= "C:\Service.exe"
    

    Note that MyService is the name you give to the service at this point and it can be anything you like (within reason :-). This name will be shown in services console list.

    Once you have your service installed you would need to debug it right when OnStart is called. This can be achieved by running and attaching to a debugger (Visual Studio) from within the service:

    protected override void OnStart(string[] args)
    {
        #if DEBUG
        Debugger.Launch();
        #endif
        ...
    }
    

    Do not forget to build and replace service executable after this code change. Service must be stopped but no need to uninstall and reinstall it.

    To delete service using SC:

    sc delete MyService
    

提交回复
热议问题