将C#控制台应用程序转换为服务(主方法无法工作)

3

最近我把自己的方法“转化”或者说导入到了默认的Windows Service模板中。没有语法错误并且编译也没问题,但是FileSystemWatcher方法出了一些问题,比如当正常运行时它会将所有已创建的进程写入到process.lst中,但是作为服务运行时它却不能这样做(也许是因为工作目录的原因,因为它是一个服务?):

namespace WindowsService
{
    class WindowsService : ServiceBase
    {
        /// <summary>
        /// Public Constructor for WindowsService.
        /// - Put all of your Initialization code here.
        /// </summary>
        public WindowsService()
        {
            this.ServiceName = "My Service";
            this.EventLog.Source = "My Service";
            this.EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific
            //  type of event. Set to true if you need it, false otherwise.
            this.CanHandlePowerEvent = true;
            this.CanHandleSessionChangeEvent = true;
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.CanStop = true;

            if (!EventLog.SourceExists("My Service"))
                EventLog.CreateEventSource("My Service", "Application");
        }

        /// <summary>
        /// The Main Thread: This is where your Service is Run.
        /// </summary>
        static void Main()
        {
            ServiceBase.Run(new WindowsService());

            // This checks for any existing running instances, if found the proess is terminated immidieately.
            if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) return;

            DisplayInfo();

            string dirPath = "C:\\";
            FileSystemWatcher fileWatcher = new FileSystemWatcher(dirPath);
            fileWatcher.IncludeSubdirectories = true;
            fileWatcher.Filter = "*.exe";
            // fileWatcher.Filter = "C:\\$Recycle.Bin";   
            //  fileWatcher.Changed += new FileSystemEventHandler(FileWatcher_Changed);   
            fileWatcher.Created += new FileSystemEventHandler(FileWatcher_Created);
            //  fileWatcher.Deleted += new FileSystemEventHandler(FileWatcher_Deleted);  
            //  fileWatcher.Renamed += new RenamedEventHandler(FileWatcher_Renamed);    
            fileWatcher.EnableRaisingEvents = true;
            // updated code

            while (true)
            {
                CleanUpDel();

                StartRemoveDuplicate();

                CompareFiles();

                bool changes = ScanFileChanges();

                if (!changes)
                {
                    TrimColon("process_trim.lst", "process_trimmed.lst");

                    TrimWipe();

                    AddTMPIgnore();

                    SendAlert();

                    CompareOrig();


                }
                Thread.Sleep(10000);
            }
        }


        private static void AddTMPIgnore()
        {
            var myString = File.ReadAllText("process_final.lst");
            File.AppendAllText("ignore_temp.lst", myString);
        }



        static void FileWatcher_Created(object sender, FileSystemEventArgs e)
        {

            using (StreamWriter fileWriter = new StreamWriter("process.lst", true))
            {
                var data = true;
                fileWriter.Write("C:\\" + e.Name + Environment.NewLine);
            }


        }
2个回答

8

我已经有一段时间没有做服务了,所以我只记得一些模糊的内容:

有一个OnStart和一个OnStop方法。在其中,您必须创建一个新线程来完成工作。您可以使用BackgroundWorker或创建一个System.Threading.Thread。 如果我正确解释了您的代码,您是在Main方法中处理的。这是不允许的。服务将无法正确初始化。构造函数也不适合进行此操作。
还要确保,如果调用OnStop,则您的处理逻辑确实停止。否则,服务控制管理器将不喜欢您的服务。


关于“如果没有要做的事情,则执行NOOP循环”的先前评论是不正确的。 - skb

0

您的服务可能没有写入该文件的权限,或者将文件放在了您意料之外的位置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接