Windows服务参数作为控制台应用程序运行

时间:2016-02-29 20:41:29

标签: c# service

当我从命令提示符运行带有--console的Windows服务时,会创建console.txt文件,因此我知道ConsoleMode()方法被触发但没有任何内容写入控制台窗口。我知道Windows服务无法写入控制台,但由于我绕过ServiceBase.Run,它不应该只是作为普通的控制台应用程序运行吗?

using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ShowCheckerService
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(params string[] args)
        {



    #if DEBUG
            Service1 myService = new Service1();
            myService.OnDebug();
            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

    #else
            if (Environment.UserInteractive)
            {
                string parameter = string.Concat(args);
                switch (parameter)
                {
                    case "--install":
                        ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                        break;
                    case "--uninstall":
                        ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                        break;
                    case "--console":
                        ConsoleMode();
                        break;
                }
            }

            else
            {

                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                new Service1()
                };
                ServiceBase.Run(ServicesToRun);
            }
    #endif

        }


        private static void ConsoleMode()
        {
            System.IO.File.Create(@"C:\ProgramData\ShowChecker\console.txt");
            Console.WriteLine("asdf");            
        }


    }
}

2 个答案:

答案 0 :(得分:1)

必须在属性中更改此内容:

enter image description here

答案 1 :(得分:0)

Windows服务实际上可以写一个控制台缓冲区,实际上我曾经有一个console.read(),我的服务挂在那一行上https://stackoverflow.com/a/8793030/5601607