FileSystemWatcher 锁定文件,不释放文件

问题描述 投票:1回答:1

我现在面临一个问题,有一段时间了。搜索了很多,没有找到解决方法 :(

我有一个小程序,它应该监视一个新的文件,并打开它。当 OnFileCreated 事件触发,会出现这个错误。

IOException: The process cannot access the file 'file path' because it is being used by another process

这个文件被我的程序锁定了

会是什么问题呢?这是我的代码。

static void Main(string[] args)
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        string dirPath = @"B:\watchdir";
        watcher.Path = dirPath;
        watcher.Filter = "*.*";
        watcher.IncludeSubdirectories = false;
        watcher.Created += new FileSystemEventHandler(OnFileCreated);

        watcher.EnableRaisingEvents = true;
        new System.Threading.AutoResetEvent(false).WaitOne();
        Console.ReadKey();
    }

    private static void OnFileCreated(object sender, FileSystemEventArgs e)
    {
        try
        {
            using (var stream = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
            }
        }
        catch (Exception err)
        {
            Console.WriteLine(err.Message);
            throw;
        }
    }
c# filesystemwatcher
1个回答
0
投票

使用 FileShare.ReadWrite 而不是 FileShare.Read

using (var stream = new FileStream(e.FullPath, 
                                   FileMode.Open, 
                                   FileAccess.Read, 
                                   FileShare.ReadWrite))
        {
        }
© www.soinside.com 2019 - 2024. All rights reserved.