.Net Windows Service и FileSystemWatcher проблема

Я искал много четыре и не нашел решения нижеприведенной проблемы, я надеюсь, что кто-нибудь сможет помочь мне на этом форуме.

У меня есть служба Windows.net с двумя FSW, которая контролирует папки в сети.

структура папок \NetworkDrive\NewFolder\InputDirectory \NetworkDrive\NewFolder\WorkingDirectory

Когда я копирую несколько файлов в каталог \ NetworkDrive \ NewFolder \ InputDirectory, скажем, file1, file2, file3 и file4, тогда обрабатываются только file1, file2 и file3, и он оставляет один файл

Ниже приведен код класса обслуживания и класса файловой системы.

Класс обслуживания

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using System.Security.Permissions;

namespace Service1
{
    public partial class Service1 : ServiceBase
    {
    public FaxInbound()
    {
        InitializeComponent();
        this.ServiceName = "Service1";
    }

    protected override void OnStart(string[] args)
    {
        onServiceStartProcess();
    }

    protected override void OnStop()
    {
        try
        {
        workingSysTimer.Enabled = false;
        inboundSysTimer.Enabled = false;
        workingSysTimer.Stop();
        inboundSysTimer.Stop();
        }
        catch (ApplicationException ex)
        {
        throw new ProblemException(ex.Message, ex.InnerException);
        }
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    private void inboundSysTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        try
        {
        WatchFileSystem.Run(inboundFSW, inputDirectory, directoryWatchfilter);
        }
        catch (ApplicationException ex)
        {
        throw new ProblemException(ex.Message, ex.InnerException);
        }
        finally
        {
        inboundSysTimer.Enabled = true;
        inboundSysTimer.Start();
        }
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    private void workingSysTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        try
        {
        WatchFileSystem.Run(workingFSW, workingDirectory, directoryWatchfilter);
        }
        catch (ApplicationException ex)
        {
        throw new ProblemException(ex.Message, ex.InnerException);
        }
        finally
        {
        workingSysTimer.Enabled = true;
        workingSysTimer.Start();
        }
    }

    internal void onServiceStartProcess()
    {
        try
        {
        setConfig();
        inboundSysTimer.Enabled = true;
        workingSysTimer.Enabled = true;
        inboundSysTimer.Start();
        workingSysTimer.Start();
        }
        catch (ApplicationException ex)
        {
        throw new ProblemException(ex.Message, ex.InnerException);
        }
    }
    }
}

Класс FileSystemwatcher

using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
using System.Security.Permissions;

namespace Service1
{
    [Serializable()]
    internal class WatchFileSystem
    {
    [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
    internal static void Run(System.IO.FileSystemWatcher watcher, string directoryPath = "", string fileFilter = "*.*")
    {
        try
        {
        string args = directoryPath;

        if (args.Length < 3)
        {
            return;
        }

        watcher.Path = args;

        watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.DirectoryName | NotifyFilters.FileName;

        watcher.Filter = fileFilter;
        watcher.InternalBufferSize = 64;

        if (watcher.Path == inputDirectory)
        {
            watcher.Changed += new FileSystemEventHandler(OnInputDirectoryChanged);
            watcher.Created += new FileSystemEventHandler(OnInputDirectoryChanged);
            watcher.Error += new ErrorEventHandler(OnInputDirectoryError);
        }

        if (watcher.Path == workingDirectory)
        {
            watcher.Changed += new FileSystemEventHandler(OnWorkingDirectoryChanged);
            watcher.Created += new FileSystemEventHandler(OnWorkingDirectoryChanged);
            watcher.Error += new ErrorEventHandler(OnWorkingDirectoryError);
        }

        watcher.EnableRaisingEvents = true;
        }
        catch (ApplicationException ex)
        {
        throw new ProblemException(ex.Message, ex.InnerException);
        }
    }


    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    internal static void OnInputDirectoryChanged(object source, FileSystemEventArgs e)
    {
        try
        {
        System.IO.FileStream file = null;
        try
        {
            if (System.IO.File.Exists(e.FullPath) == true)
            {
            file = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
        }
        catch (IOException)
        {
            System.Threading.Thread.Yield();
            System.Threading.Thread.Sleep(100); // hack for timing issues
            return;
        }
        finally
        {
            if (file != null)
            file.Dispose();
        }

        if (e.ChangeType == WatcherChangeTypes.Created)
        {
            System.IO.FileInfo infoFile = new System.IO.FileInfo(e.FullPath);
            if (infoFile.Exists == true)
            {
            infoFile = null;
            try
            {
                if (file != null)
                {
                file.Close();
                file.Dispose();
                }

                if (System.IO.File.Exists(e.FullPath) == true)
                {
                if (System.IO.File.Exists(System.IO.Path.Combine(workingDirectory, e.Name)) == false)
                {
                    System.IO.File.Move(e.FullPath, System.IO.Path.Combine(workingDirectory, e.Name));
                }
                }
            }
            catch (IOException)
            {
                System.Threading.Thread.Yield();
                System.Threading.Thread.Sleep(100); // hack for timing issues   
                return;
            }
            }
        }
        }
        catch (ApplicationException ex)
        {
        throw new ProblemException(ex.Message, ex.InnerException);
        }
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    private static void OnInputDirectoryError(object source, ErrorEventArgs e)
    {
        System.IO.FileSystemWatcher inboundFSW = new System.IO.FileSystemWatcher();
        inboundFSW.EnableRaisingEvents = true;
        inboundFSW.IncludeSubdirectories = false;

        while (!inboundFSW.EnableRaisingEvents)
        {
        try
        {
            WatchFileSystem.Run(inboundFSW, inputDirectory, directoryWatchfilter);
        }
        catch
        {
            System.Threading.Thread.Sleep(5000);
        }
        }
    }


    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    internal static void OnWorkingDirectoryChanged(object source, FileSystemEventArgs e)
    {
        try
        {
        System.IO.FileStream file = null;
        try
        {   
            if (System.IO.File.Exists(e.FullPath) == true)
            {
            file = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
        }
        catch (IOException)
        {
            System.Threading.Thread.Yield();
            System.Threading.Thread.Sleep(100); // hack for timing issues   
            return;
        }
        finally
        {
            if (file != null)
            file.Dispose();
        }

        if (e.ChangeType == WatcherChangeTypes.Created)
        {
            System.IO.FileInfo infoFile = new System.IO.FileInfo(e.FullPath);
            if (infoFile.Exists == true)
            {
            infoFile = null;
                try
                {
                if (file != null)
                {
                    file.Close();
                    file.Dispose();
                }

                if (System.IO.File.Exists(e.FullPath) == true)
                {
                    generateFiles(System.IO.Path.Combine(workingDirectory, e.Name));
                }
                }
                catch (IOException)
                {
                System.Threading.Thread.Yield();
                System.Threading.Thread.Sleep(100); // hack for timing issues  
                return;
                }
            }
        }
        }
        catch (ApplicationException ex)
        {
        throw new ProblemException(ex.Message, ex.InnerException);
        }
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    private static void OnWorkingDirectoryError(object source, ErrorEventArgs e)
    {
        System.IO.FileSystemWatcher workingFSW = new System.IO.FileSystemWatcher();
        workingFSW.EnableRaisingEvents = true;
        workingFSW.IncludeSubdirectories = false;

        while (!workingFSW.EnableRaisingEvents)
        {
        try
        {
            WatchFileSystem.Run(workingFSW, workingDirectory, directoryWatchfilter);
        }
        catch
        {
            System.Threading.Thread.Sleep(5000);
        }
        }
    }
    }
}

Любая помощь будет оценена.

1 ответ

Если вы все еще не нашли ответ, пожалуйста, обратитесь к: FileSystemWatcher проблемы

Рассматривали ли вы вместо этого использование системы голосования? Вы можете создать новую тему, проверить новые файлы и скопировать / переместить их, а затем использовать Thread.Sleep() положить поток спать в течение определенного промежутка времени по вашему выбору. И цикл через этот процесс.

Другие вопросы по тегам