2

我正在尝试创建一个简单的应用程序,它将所有写入某个目录的文件移动到另一个目录。那是我的问题:如果我在我的目录中一次写入 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);
    }
}

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

4

1 回答 1

0

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);
            }
        }       
    }
于 2012-09-05T10:20:47.210 回答