我收到一个无法从命令行或debbuger启动服务的错误 [英] I m getting an error that cannot start service from command line or debbuger

查看:88
本文介绍了我收到一个无法从命令行或debbuger启动服务的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

windows service should be first install and then started with server explorer,administrative tools or the net start command





这是我面临的错误。我尝试从计算机管理启动服务 - 服务和应用程序,通过管理员权限运行cmd。

以下我附上我的代码。







this is the error i m facing. I have tried starting the service from computer management - service and application, running cmd through admin rights.
below i m attaching my code.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        private Timer timer1 = null;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer1 = new Timer();
            this.timer1.Interval = 60000; //60 sec
            this.timer1.Elapsed +=new System.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled=true;
            Library.WriteErrorLog("test windows service started");
            
        }

        protected override void OnStop()
        {
            timer1.Enabled = false;
            Library.WriteErrorLog("Test Service ended");
        }

        public void timer1_Tick(object sender, ElapsedEventArgs e)
        {
            //job
            var result = RunProcess(@"c:\", "webupknvp.Bat", "", false);
            if (result == 0)
            {
                // success
                Console.WriteLine("Sucess");
            }
            else
            {
                // failed ErrorLevel / app ExitCode
                Console.WriteLine("failed try again");
                
            }
            

        }

        public int RunProcess(string workDir, string appName, string args, bool hide = false)
            {
                    
                    Process proc = null;
                    proc = new Process();          
                    string batrun = string.Format("cmd.exe", "/c" + @"C:\Abhay\batfile"); // or @"C:\Abhay\batfile" in the end ("cmd.exe", "/c" + @"C:\Abhay\batfile")
                    proc.StartInfo.UseShellExecute = false;   //addition   	
                    proc.StartInfo.WorkingDirectory = workDir;//batrun
	                proc.StartInfo.FileName = appName;
                    proc.StartInfo.Arguments = args;
	                proc.StartInfo.CreateNoWindow = hide;
                    
	                proc.Start();
	                proc.WaitForExit();
	
	                return proc.ExitCode;
               }
    }
}





图书馆类





library class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace WindowsService1
{
    public static class Library
    {
        public static void WriteErrorLog(Exception ex)
        {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\ Logfile.txt", true);
                sw.WriteLine(DateTime.Now.ToString() + ":" + ex.Source.ToString().Trim() + ";" + ex.Message.ToString().Trim());
                sw.Flush();
                sw.Close();

            }
            catch
            {

            }
        }

        public static void WriteErrorLog(string Message)
        {
            StreamWriter sw = null;
            try
            { 
            
                sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\ Logfile.txt", true);
                sw.WriteLine(DateTime.Now.ToString() + ":" + Message);
                sw.Flush();
                sw.Close();
            }
            catch
            {

            }
        }
    }
}





program.cs







program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace WindowsService1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new Service1() 
            };
            ServiceBase.Run(ServicesToRun);
           
        }
    }
}





我尝试过:





What I have tried:

I have tried starting the service from computer management - service and application, running cmd through admin rights.

推荐答案

其他的评论是好的和正确的。我只是不想分享我在开发Windows服务时使用的方法。



我不想在调试期间快速测试unistall / install服务,所以我将它们作为控制台应用程序运行。



所以我使用
other's comments are good and right. i just wan't to share the approach I use when developing Windows Services.

I don't want to unistall/install Service for a quick test during debug so I run them as console-applications.

So I use
Environment.UserInteractive

来检查我是否从用户运行 - 交互(例如在调试期间,或者只是单击WindowsExplorer中的exe) - >如果为true,我将服务作为控制台运行,通过反射调用服务的OnStart方法...

所以我的解决方案看起来像这样(评论和跟踪无效)



帮助库中的某个地方(它是通用的,适用于所有服务 - 只需尝试一下):



to check if I run from user-interaction (e.g. during debug, or by just clicking on the exe in WindowsExplorer) -> if true, I run the Service as console, by calling the OnStart-Method of the Service by reflection...
So my solution looks like this (comments and tracing ommited)

Somewhere in a helper library (it's generic and will work for all Services - just try it out):

public static void RunServices(ServiceBase[] aServicesToRun, string[] astrArgs)
{
    if (Environment.UserInteractive)
    {
        // run as console
        try
        {
            CallServiceMethod(aServicesToRun, "OnStart", new object[] { astrArgs });
            WaitPrompt(aServicesToRun);
            CallServiceMethod(aServicesToRun, "OnStop", null);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Service-call failed: " + ex.ToString());
            Console.ReadKey(true);
        }
    }
    else
    {
        // run as Windows service
        ServiceBase.Run(aServicesToRun);
    }
}










static void CallServiceMethod(ServiceBase[] aServicesToRun, string strMethodName, object[] aobjParams)
{
    Type type = typeof(ServiceBase);
    BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
    MethodInfo method = type.GetMethod(strMethodName, flags);

    foreach (ServiceBase service in aServicesToRun)
        method.Invoke(service, aobjParams);
}







private static void WaitPrompt(ServiceBase[] aServicesToRun)
{
    ConsoleKeyInfo key;

    do
    {
        key = Console.ReadKey(true);

        switch (key.Key)
        {
            case ConsoleKey.P:
                CallServiceMethod(aServicesToRun, "OnPause", null);
                Console.WriteLine("Action> PAUSE");
                break;
            case ConsoleKey.R:
                CallServiceMethod(aServicesToRun, "OnContinue", null);
                Console.WriteLine("Action> RESUME");
                break;
            case ConsoleKey.S:
                 // Service-Method OnStop will be called after this method ends
                 Console.WriteLine("Action> STOP");
                break;
        }
    } while (key.Key != ConsoleKey.S);
}





然后在我的服务实现中,我这样使用它:





Then in my Service-implementation I use it like this:

static void Main(string[] astrArgs)
{
    ServiceExecutionHelper.RunServices(new ServiceBase[] { new MyService() }, astrArgs);
    // replaces ServiceBase.Run(...);
}





也许对你有用...



Maybe useful for you too...


这可能有帮助:使用C#创建基本Windows服务 [ ^ ]
This may help: Creating a Basic Windows Service in C#[^]


您必须先安装您的服务(例如,参见解决方案1中提供的CodeProject文章末尾)。



然后使用错误消息中提到的方法之一启动它。



请参阅以下链接,从命令行启动和停止服务:

使用SC控制服务(Windows) [ ^ ]

净启动 [ ^ ]
You have to install your service first (see for example at the end of the CodeProject article provided in solution 1).

Then start it using one of the methods mentioned in the error message.

See these links for starting and stopping services from the command line:
Controlling a Service Using SC (Windows)[^]
Net start[^]


这篇关于我收到一个无法从命令行或debbuger启动服务的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆