文件系统观察器锁定文件,不会释放它



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

我有一个小程序,应该监视一个新文件,然后打开它。触发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;
}
}

使用FileShare.ReadWrite而不是FileShare.Read

using (var stream = new FileStream(e.FullPath, 
FileMode.Open, 
FileAccess.Read, 
FileShare.ReadWrite))
{
}

最新更新