简体   繁体   English

C# .NET BackgroundWorker 6 FileSystemWatcher 该进程无法访问文件“PATH”,因为它正被另一个进程使用

[英]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.

相关问题 FileSystemWatcher C# - 无法访问文件,因为它正被另一个进程使用 - FileSystemWatcher C# - cannot access file because it is being used by another process FileSystemWatcher无法访问文件,因为它正在被另一个进程使用 - FileSystemWatcher cannot access file because its being used by another process IOException:该进程无法访问文件“文件路径”,因为它正在被C#控制台应用程序中的另一个进程使用 - IOException: The process cannot access the file 'file path' because it is being used by another process in Console Application in C# 该进程无法访问该文件,因为它正被另一个进程asp.net c#使用? - The process cannot access the file because it is being used by another process asp.net c#? c#无法访问文件,因为它正被另一个进程使用 - c# Cannot access file because it is being used by another process 该进程无法访问文件“路径”,因为它正在被另一个进程使用 - The process cannot access the file 'path' because it is being used by another process c# ZipFile.CreateFromDirectory - 进程无法访问文件“path_to_the_zip_file_created.zip”,因为它正被另一个进程使用 - c# ZipFile.CreateFromDirectory - the process cannot access the file "path_to_the_zip_file_created.zip" because it is being used by another process 进程无法访问文件,因为它被另一个进程使用 - c# - Process cannot access file because it is used by another process C# 进程无法访问文件,因为它正被另一个进程使用 - C# process cannot access file because it is being used by another process 该进程无法访问文件“ * .Yap”,因为它正在被另一个进程C#使用 - The process cannot access the file '*.Yap' because it is being used by another process C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM