Folder listener without using FilesystemWatcher

蓝咒 提交于 2020-01-03 05:12:32

问题


I need to create a listener in C# that will watch a shared folder (UNC path) and copy the files with a specific extension (*.json) to a target folder when they arrive. The files can be delayed for about half a minute. The folder is never empty.

Problems:

  1. The files will arrive in a new sub folder, FileSystemWatcher can't be used since it can't listen to sub folders in a shared folder.

  2. The files needs to be copied and left in the folder, so we need to assure that the same file isn't copied more than once.

  3. Files that are edited/updated needs to be copied again and overwritten in the target folder.

  4. Other files will be in the folder and new files will arrive that we need to ignore (doesn't have the right extension).

I thought about polling the folder , but I didn't come up with a good implementation.

I'm pretty sure I can't use the FilesystemWatcher object, but maybe someone can find a smart solution for using it.


回答1:


One solution to your problem could be you can check the location constantly for a while and examine changes by yourself.

it is not a complete solution, but an idea to consider.

    public async Task FindMyFile(string filePath)
    {           
        int retries = 0;
        this.Founded = false;
        while (!this.Founded)
        {
            if (System.IO.File.Exists(filePath))
                this.Founded = true;
            else if (retries < this.maxTries)
            {
                Console.WriteLine($"File {filePath} not found. Going to wait for 15 minutes");
                await Task.Delay(new TimeSpan(0, 15, 0));
                ++retries;
            }
            else
            {
                Console.WriteLine($"File {filePath} not found, retries exceeded.");
                break;
            }
        }
    }


来源:https://stackoverflow.com/questions/45094991/folder-listener-without-using-filesystemwatcher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!