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

将C#控制台应用程序转换为服务(主方法不起作用),c#,.net,windows,C#,.net,Windows,我最近已将我的方法“转换”或导入到默认的Windows服务模板中。没有语法错误,其编译正常,但FileSystemWatcher方法由于某些原因不起作用,例如,正常运行时,它会将已创建的所有进程写入process.lst,但作为服务运行时,它不会这样做(可能与工作目录有关,因为它是服务?) 命名空间窗口服务 { 类WindowsService:ServiceBase { /// ///WindowsService的公共构造函数。 ///-将所有初始化代码放在此处。 /// 公共服务 { th

我最近已将我的方法“转换”或导入到默认的Windows服务模板中。没有语法错误,其编译正常,但FileSystemWatcher方法由于某些原因不起作用,例如,正常运行时,它会将已创建的所有进程写入process.lst,但作为服务运行时,它不会这样做(可能与工作目录有关,因为它是服务?)

命名空间窗口服务
{
类WindowsService:ServiceBase
{
/// 
///WindowsService的公共构造函数。
///-将所有初始化代码放在此处。
/// 
公共服务
{
this.ServiceName=“我的服务”;
this.EventLog.Source=“我的服务”;
this.EventLog.Log=“应用程序”;
//这些标志设置是否处理该特定事件
//事件类型。如果需要,请将其设置为true,否则设置为false。
this.CanHandlePowerEvent=true;
this.CanHandleSessionChangeEvent=true;
this.CanPauseAndContinue=true;
this.CanShutdown=true;
this.CanStop=true;
如果(!EventLog.SourceExists(“我的服务”))
CreateEventSource(“我的服务”、“应用程序”);
}
/// 
///主线程:这是运行服务的地方。
/// 
静态void Main()
{
运行(新的WindowsService());
//这将检查是否存在任何正在运行的实例,如果发现该进程立即终止。
if(System.Diagnostics.Process.GetProcessByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count()>1)返回;
DisplayInfo();
字符串dirPath=“C:\\”;
FileSystemWatcher fileWatcher=新的FileSystemWatcher(dirPath);
fileWatcher.IncludeSubdirectories=true;
fileWatcher.Filter=“*.exe”;
//fileWatcher.Filter=“C:\\$Recycle.Bin”;
//fileWatcher.Changed+=新文件系统EventHandler(fileWatcher\u已更改);
fileWatcher.Created+=新文件系统EventHandler(fileWatcher_Created);
//fileWatcher.Deleted+=新的文件系统EventHandler(fileWatcher\u已删除);
//fileWatcher.重命名+=新重命名的EventHandler(fileWatcher_重命名);
fileWatcher.EnableRaisingEvents=true;
//更新代码
while(true)
{
CleanUpDel();
StartRemoveDuplicate();
比较文件();
bool changes=ScanFileChanges();
如果(!更改)
{
Trimclon(“过程修剪.lst”、“过程修剪.lst”);
TrimWipe();
AddTMPIgnore();
SendAlert();
compareOrg();
}
睡眠(10000);
}
}
私有静态void AddTMPIgnore()
{
var myString=File.ReadAllText(“process_final.lst”);
AppendAllText(“ignore_temp.lst”,myString);
}
已创建静态无效FileWatcher_(对象发送方、文件系统目标)
{
使用(StreamWriter fileWriter=newstreamwriter(“process.lst”,true))
{
var数据=真;
fileWriter.Write(“C:\\”+e.Name+Environment.NewLine);
}
}

我已经做了很长时间的最后一次保养,因此我只记得模糊不清,但:

有一个和一个OnStop方法。在此方法中,您必须创建一个执行此任务的新线程。您可以使用或创建System.Threading.thread。 当我正确解释您的代码时,您将在Main方法中进行处理。这是不允许的。服务将不会正确初始化。构造函数也不是执行此操作的地方。

还请确保,如果调用OnStop,您的处理逻辑确实停止。否则,服务控制管理器将不喜欢您的服务。

您的服务可能没有写入文件的权限,或者它正在将文件放在您不期望的地方。

前面关于“无事可做时NOOP loop”的注释不正确。
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);
            }


        }