【问题标题】:Missing events on catching from FileSystemWatcher C#从 FileSystemWatcher C# 捕获缺少事件
【发布时间】:2012-09-05 18:20:47
【问题描述】:

我正在尝试创建一个简单的应用程序,它将写入某个目录的所有文件移动到另一个目录。那是我的问题:如果我在我的目录中一次写入 10000 个以外的文件(超过 1KB 的小 .txt 文件) - 其中一些没有处理移动到输出目录。我正在使用 FileSystemWatcher 事件处理程序来解决这个问题。这是我的代码示例:

Class MyProgramm
{
    void Process(Object o, FileSystemEventArgs e)
    {
        //do something with e.Name file
    }
    void main()
    {
        var FSW = New FileSystemWatcher{Path = "C:\\InputDir"};
        FSW.Created += Process;
        FSW.EnableRisingEvents = true;
        Thread.Sleep(Timeout.Infinite);
    }
}

最后,我们处理了一些文件,但一些写入的文件仍未处理.. 有什么建议吗?

【问题讨论】:

标签: c# events


【解决方案1】:

我在使用 FileSystemWatcher 时遇到了类似的问题。它似乎经常“丢球”。我通过扩展“ServiceBase”来寻求替代解决方案,自从它作为 Windows 服务上线以来,它一直在工作。希望这会有所帮助:

    public partial class FileMonitor : ServiceBase
    {
        private Timer timer;
        private long interval;
        private const string ACCEPTED_FILE_TYPE = "*.csv";

        public FileMonitor()
        {           
            this.ServiceName = "Service";
            this.CanStop = true;
            this.CanPauseAndContinue = true;
            this.AutoLog = true;
            this.interval = long.Parse(1000);
        }

        public static void Main()
        {
            ServiceBase.Run(new FileMonitor());
        }

        protected override void OnStop()
        {
            base.OnStop();
            this.timer.Dispose();
        }

        protected override void OnStart(string[] args)
        {
            AutoResetEvent autoEvent = new AutoResetEvent(false);
            this.timer = new Timer(new TimerCallback(ProcessNewFiles), autoEvent, interval, Timeout.Infinite);
        }

        private void ProcessNewFiles(Object stateInfo)
        {
            DateTime start = DateTime.Now;
            DateTime complete = DateTime.Now;

            try
            {
                string directoryToMonitor = "c:\mydirectory";
                DirectoryInfo feedDir = new DirectoryInfo(directoryToMonitor);
                FileInfo[] feeds = feedDir.GetFiles(ACCEPTED_FILE_TYPE, SearchOption.TopDirectoryOnly);             

                foreach (FileInfo feed in feeds.OrderBy(m => m.LastWriteTime))
                {
                    // Do whatever you want to do with the file here
                }
            }
            finally
            {
                TimeSpan t = complete.Subtract(start);
                long calculatedInterval = interval - t.Milliseconds < 0 ? 0 : interval - t.Milliseconds;
                this.timer.Change(calculatedInterval, Timeout.Infinite);
            }
        }       
    }

【讨论】:

  • 感谢您的回答!问题出在 FileSystemWatcher 的 InternalBufferSize 属性中!默认情况下,它等于 8192 个字节,而每个事件从中获取 16 个字节。我只是增加了这个属性的价值!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
  • 2018-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多