[C#在事件上崩溃

问题描述 投票:0回答:1

我正在尝试将C#服务创建为控制台应用程序。

主要代码:

static void Main(string[] args)
{
        var exitCode = HostFactory.Run(
            x =>
            {
                x.Service<HeartBeat>(s =>
                {
                    s.ConstructUsing(heartbeat => new HeartBeat());
                    s.WhenStarted(heartbeat => heartbeat.Start());
                    s.WhenStopped(heartbeat => heartbeat.Stop());
                });

                x.RunAsLocalSystem();
                x.SetServiceName("UpgradeServices");
                x.SetDisplayName("Service Upgrade");
                x.SetDescription("Service is monitoring new version.");
            });

        int exitCodeValue = (int)Convert.ChangeType(exitCode, exitCode.GetTypeCode());
        Environment.ExitCode = exitCodeValue;
}

然后,我有如下代码用于删除和复制文件:

public class MovingFiles
{
    public string fileName;
    public string destPath;
    private DirectoryInfo directory;
    private DirectoryInfo myFile;
    public string sourcePath;
    public string targetPath;

    public MovingFiles(string sourceFolder, string targetFolder)
    {
        sourcePath = sourceFolder;
        targetPath = targetFolder;
    }

    public void deleteFilesMethod()
    {
        System.Threading.Thread.Sleep(10000);
        string deleteString;
        //First we want to delete all files except for the JSON file as this has all of the important settings
        if (System.IO.Directory.Exists(targetPath))
        {
            string[] files = System.IO.Directory.GetFiles(targetPath);

            // Loop through each files and then delete these if they are not the JSON file
            foreach (string s in files)
            {
                deleteString = targetPath;
                // The file name which is returned will be deleted
                fileName = System.IO.Path.GetFileName(s);

                if (fileName != "appsettings.json")
                {
                    deleteString = System.IO.Path.Combine(targetPath, fileName);

                    try
                    {
                        System.IO.File.Delete(deleteString);
                    }
                    catch (System.IO.IOException e)
                    {
                        Console.WriteLine(e.Message);
                        return;
                    }
                }
            }
        }
        else
        {
            Console.WriteLine("The loop didn't run, source path doesn't exist");
        }
    }

    public void copyFilesMethod()
    {
        System.Threading.Thread.Sleep(10000);

        if (System.IO.Directory.Exists(sourcePath))
        {
            // Searching for the latest directory created in the sourcePath folder
            directory = new DirectoryInfo(sourcePath);
            myFile = (from f in directory.GetDirectories()
                      orderby f.LastWriteTime descending
                      select f).First();

            sourcePath = System.IO.Path.Combine(sourcePath, myFile.Name);
            string[] files = System.IO.Directory.GetFiles(sourcePath);

            // Copy the files and overwrite destination files if they already exist.
            foreach (string s in files)
            {
                // Use static Path methods to extract only the file name from the path.
                fileName = System.IO.Path.GetFileName(s);

                if (fileName != "appsettings.json")
                {

                    destPath = System.IO.Path.Combine(targetPath, fileName);

                    try
                    {
                        System.IO.File.Copy(s, destPath, true);
                    }
                    catch (System.IO.IOException e)
                    {
                        Console.WriteLine(e.Message);
                        return;
                    }
                }
            }
        }
        else
        {
            Console.WriteLine("The loop didn't run, source path doesn't exist");
        }

        // Keep console window open in debug mode.
        Console.WriteLine("Procedure has been completed.");
}

一旦有一个新文件被写入,应立即触发:

class FileMonitor
{
    public FileSystemWatcher watcher = new FileSystemWatcher();
    public string sourcePath;
    public string targetPath;

    public FileMonitor(string sourceFolder, string targetFolder)
    {
        sourcePath = sourceFolder;
        targetPath = targetFolder;
    }

    public void watch()
    {
            watcher.Path = sourcePath;
            watcher.NotifyFilter =  NotifyFilters.LastWrite
                                   | NotifyFilters.FileName | NotifyFilters.DirectoryName
                                   | NotifyFilters.CreationTime;
            //var one = NotifyFilters.FileName;
            watcher.Filter = "*.*";
            watcher.Created += new FileSystemEventHandler (OnChanged);
            watcher.EnableRaisingEvents = true;
            //System.Threading.Thread.Sleep(25000);
    }

    public void OnChanged(object source, FileSystemEventArgs e)
    {
        //Copies file to another directory.
        MovingFiles FileMoveOne = new MovingFiles(sourcePath, targetPath);
        FileMoveOne.deleteFilesMethod();
        FileMoveOne.copyFilesMethod();

    }
}

我理解下面的内容后,如果有新文件,然后每隔10秒就会出现一次,然后触发OnChange方法,对吗?

public class HeartBeat
{
    private readonly Timer _timer;

    public HeartBeat()
    {
        _timer = new Timer(10000)
        {
            AutoReset = true
        };
        _timer.Elapsed += TimerElapsed;
    }

    private void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        //StringBuilder loggingLine = new StringBuilder();
        /* Every 30 seconds it will write to the file */
        string[] lines = new string[] {DateTime.Now.ToString() + ": Heartbeat is active. Service is monitoring SS and DS"};
        //lines[1] = DateTime.Now.ToString() + " About to check if new files are placed on server";

            //loggingLine.Append(lines[i]);
            File.AppendAllLines(@"C:\Users\RLEBEDEVS\Desktop\Monitor\Monitor1\HeartBeat.log", lines);
        //File.AppendAllLines(@"C:\Users\RLEBEDEVS\Desktop\Monitor\Monitor1\HeartBeat.log", lines);
        FileMonitor versioOne = new FileMonitor(@"C:\Users\RLEBEDEVS\Desktop\Monitor\Monitor1", @"C:\Users\RLEBEDEVS\Desktop\Monitor\Monitor2");
        versioOne.watch();
    }

    public void Start ()
    {
        _timer.Start();
    }

    public void Stop ()
    {
        _timer.Stop();
    }
}

我遇到的问题是不一致的。

  1. 创建新文件夹后,应将文件复制到Monitor2文件夹,但第一次创建时不这样做。一旦在monitor1文件夹中创建了一个文件夹,它将第二次删除并复制文件。

  2. 每秒钟尝试复制文件时,它崩溃并显示以下错误,我不熟悉:

    Topshelf.Hosts.ConsoleRunHost严重:0:服务引发了未处理的异常System.UnauthorizedAccessException:拒绝访问路径'C:\ Users \ RLEBEDEVS \ Desktop \ Monitor \ Monitor2 \ System.Net.Sockets.dll' 。在System.IO .__ Error.WinIOError(Int32 errorCode,可能是StringFullPath)在System.IO.File.InternalDelete(字符串路径,布尔checkHost)在System.IO.File.Delete(字符串路径)在C:\ Users \ RLEBEDEVS \ Desktop \ C#\ Service \ UpgradeServices \ MovingFIles.cs:line 48中的UpgradeServices.MovingFiles.deleteFilesMethod()中在C:\ Users \ RLEBEDEVS \ Desktop \ C#\ Service \ UpgradeServices \ FileMonitor.cs:line 43中的UpgradeServices.FileMonitor.OnChanged(对象源,FileSystemEventArgs e)在System.IO.FileSystemWatcher.OnCreated(FileSystemEventArgs e)在System.IO.FileSystemWatcher.NotifyFileSystemEventArgs处(Int32操作,字符串名称)在System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode,UInt32 numBytes,NativeOverlapped * overlaypedPointer)在System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode,UInt32 numBytes,NativeOverlapped * pOVERLAP)

    Topshelf.Hosts.ConsoleRunHost信息:0:停止UpgradeServices服务Topshelf.Hosts.ConsoleRunHost信息:0:UpgradeServices服务已停止。

    程序“ [497452] UpgradeServices.exe”已退出,代码为1067(0x42b)。

第48行是此行,尽管它执行了以前很好的任务(第一次执行)。

System.IO.File.Delete(deleteString);

我发现问题与提出活动的方式有关。有人知道我应该更改什么才能获得所需的结果,即在最终确定的每个新文件夹上启动服务时,它将执行移动和删除文件的两种方法?该文件夹将始终仅创建新文件夹。

问候,

c# events filesystemwatcher
1个回答
2
投票

[似乎您在心跳中每10秒开始新的FileMonitor,因此20秒后,您将有2个FileMonitor正在观看并移动(删除)相同的文件。例如,只需使用FileMonitor启动一次hosted service。或在HeartBeat类中删除计时器处理程序部分,然后在构造函数中创建FileMonitor

public HeartBeat()
{
    FileMonitor versioOne = new 
    FileMonitor(@"C:\Users\RLEBEDEVS\Desktop\Monitor\Monitor1", @"C:\Users\RLEBEDEVS\Desktop\Monitor\Monitor2");
    versioOne.watch(); 
   // may be save it to instance field so it does not get garbage collected.
   // Not sure how FileSystemWatcher behaves with subscription, 
   // it should prevent the "versionOne" from being collected via subscription.
}
© www.soinside.com 2019 - 2024. All rights reserved.