[英]C# .NET BackgroundWorker 6 FileSystemWatcher The process cannot access the file "PATH" because it is being used by another process
I'm trying to watch a directory for newly added files ending in .csv
do something with them, delete the file and wait for a newly added file to do process the file again.我正在尝试查看以
.csv
结尾的新添加文件的目录对它们执行某些操作,删除文件并等待新添加的文件再次处理该文件。 I'm using a BackgroundService
with the following code:我正在使用具有以下代码的
BackgroundService
:
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly IProcessFileService _processFileService;
private ApplicationOptions _applicationOptions;
private FileSystemWatcher _watcher = new();
public Worker(ILogger<Worker> logger, IProcessFileService processFileService, IOptions<ApplicationOptions> applicationOptions)
{
_logger = logger;
_processFileService = processFileService;
_applicationOptions = applicationOptions.Value;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
string filePath = _applicationOptions.InputDirectory;
_watcher.Path = filePath;
_watcher.EnableRaisingEvents = true;
_watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime | NotifyFilters.LastWrite;
_watcher.Filter = "*.csv*";
_watcher.Created += new FileSystemEventHandler(OnFileCreated);
return Task.CompletedTask;
}
private async void OnFileCreated(object sender, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Created)
{
await HandleAddedFile();
}
}
private async Task HandleAddedFile()
{
try
{
await _processFileService.ProcessFile();
}
catch(Exception ex)
{
_logger.LogError("{error}", ex.Message);
}
_processFileService.DeleteFileAndLog();
}
}
Works fine for the first time, but when trying inserting a second file in the directory, I get the error: The process cannot access the file "PATH" because it is being used by another process.第一次工作正常,但是当尝试在目录中插入第二个文件时,出现错误:进程无法访问文件“PATH”,因为它正被另一个进程使用。
Processing the label includes some async work, how can I fix this issue?处理 label 包括一些异步工作,我该如何解决这个问题?
I've followed the thread that Robert linked me;我已经关注了罗伯特给我的链接; I had to rewrite some stuff, but I've got it to work now using the following code.
我不得不重写一些东西,但现在我已经使用以下代码让它工作了。 I also had to modify some functions to take in the fullpath.
我还必须修改一些函数以获取完整路径。
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly IProcessFileService _processFileService;
private ApplicationOptions _applicationOptions;
private FileSystemWatcher _watcher = new();
public Worker(ILogger<Worker> logger, IProcessFileService processFileService, IOptions<ApplicationOptions> applicationOptions)
{
_logger = logger;
_processFileService = processFileService;
_applicationOptions = applicationOptions.Value;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
string filePath = _applicationOptions.InputDirectory;
_watcher.Path = filePath;
_watcher.EnableRaisingEvents = true;
_watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime | NotifyFilters.LastWrite;
_watcher.Filter = "*.csv*";
_watcher.Created += new FileSystemEventHandler(OnFileCreated);
return Task.CompletedTask;
}
private async void OnFileCreated(object sender, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Created)
{
await HandleAddedFile(e);
}
}
static FileStream? WaitForFile(string fullPath, FileMode mode, FileAccess access, FileShare share)
{
for (int numTries = 0; numTries < 10; numTries++)
{
FileStream? fs = null;
try
{
fs = new FileStream(fullPath, mode, access, share);
return fs;
}
catch (IOException)
{
fs?.Dispose();
Thread.Sleep(50);
}
}
return null;
}
private async Task HandleAddedFile(FileSystemEventArgs e)
{
FileStream? fileStream = null;
try
{
fileStream = WaitForFile(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
await _processFileService.ProcessFile(e.FullPath);
}
catch(Exception ex)
{
_logger.LogError("{error}", ex.Message);
}
fileStream?.Dispose();
_processFileService.DeleteFileAndLog(e.FullPath);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.