#c# #file-watcher
#c# #наблюдатель за файлами
Вопрос:
У меня есть несколько файлов, которые записаны в папку.Сначала записываются 2 файла, а через 10-20 минут следующие 2 файла.
Мой вопрос:
Есть ли какой-либо возможный способ сообщить наблюдателю файловой системы подождать, пока все 4 файла не окажутся в папке, прежде чем выполнять мой код?
Комментарии:
1. Создайте класс и создайте событие, которое срабатывает, когда присутствуют все 4 записи
2. Если вы знаете имя последнего файла, который будет записан, вы можете использовать свойство Filter для ожидания только событий, относящихся к этому файлу.
Ответ №1:
Согласно предложению @BugFinder, я создал нечто подобное, но не тестировал. Надеюсь, это полезно:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace CustomFileWatcher
{
public class CustomFileWatcher : IDisposable
{
private FileSystemWatcher fileWatcher;
private IList<string> fileList;
private IList<string> createdFiles;
public event EventHandler FilesCreated;
protected void OnFilesCreated(EventArgs e)
{
var handler = FilesCreated;
if (handler != null)
handler(this, e);
}
public CustomFileWatcher(IList<string> waitForTheseFiles, string path)
{
fileList = waitForTheseFiles;
createdFiles = new List<string>();
fileWatcher = new FileSystemWatcher(path);
fileWatcher.Created = fileWatcher_Created;
}
void fileWatcher_Created(object sender, FileSystemEventArgs e)
{
foreach (var item in fileList)
{
if (fileList.Contains(e.Name))
{
if (!createdFiles.Contains(e.Name))
{
createdFiles.Add(e.Name);
}
}
}
if (createdFiles.SequenceEqual(fileList))
OnFilesCreated(new EventArgs());
}
public CustomFileWatcher(IList<string> waitForTheseFiles, string path, string filter)
{
fileList = waitForTheseFiles;
createdFiles = new List<string>();
fileWatcher = new FileSystemWatcher(path, filter);
fileWatcher.Created = fileWatcher_Created;
}
public void Dispose()
{
if (fileWatcher != null)
fileWatcher.Dispose();
}
}
}
Использование
class Program
{
static void Main(string[] args)
{
IList<string> waitForAllTheseFilesToBeCopied = new List<string>();
waitForAllTheseFilesToBeCopied.Add("File1.txt");
waitForAllTheseFilesToBeCopied.Add("File2.txt");
waitForAllTheseFilesToBeCopied.Add("File3.txt");
string watchPath = @"C:OutputFolder";
CustomFileWatcher customWatcher = new CustomFileWatcher(waitForAllTheseFilesToBeCopied, watchPath);
customWatcher.FilesCreated = customWatcher_FilesCreated;
}
static void customWatcher_FilesCreated(object sender, EventArgs e)
{
// All files created.
}
}