簡體   English   中英

將C#控制台應用程序轉換為服務(主要方法不起作用)

[英]Converting C# Console Application to a Service (Main method not working)

我最近“轉換”或者更確切地將我的方法導入到默認的Windows服務模板中。 沒有語法錯誤,它的編譯沒問題,但是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);
            }


        }

我已經完成了最后一次服務已經有一段時間了,所以我只記得模糊但是:

有一個OnStart和一個OnStop方法。 在此范圍內,您必須創建一個完成工作的新線程。 您可以使用BackgroundWorker或創建System.Threading.Thread。 當我正確解釋你的代碼時,你在Main方法中進行處理。 這是不允許的。 該服務將無法正確初始化。 構造函數都不是這樣做的地方。
還要確保,如果調用OnStop,您的處理邏輯就會停止。 否則,服務控制管理中心將不喜歡您的服務。

您的服務可能沒有寫入文件的權限,或者是將文件放在您不期望的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM