问题
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:
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.
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.
Files that are edited/updated needs to be copied again and overwritten in the target folder.
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