C#多线程访问FileStream文件提示已打开
来源:互联网 发布:网络金融互助平台制作 编辑:程序博客网 时间:2024/05/02 09:44
System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open)这个方法打开文件的时候是以只读共享的方式打开的,但若此文件已被一个拥有写权限的进程打开的话,就无法读取了,因此需要使用System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open,System.IO.FileAccess.Read,FileShare.ReadWrite);设置文件共享方式为读写,FileShare.ReadWrite,这样的话,就可以打开了FileStream has Lock and UnloLet's say we have a file - the one to be used with multiple processes. I start with an assumption that file gets Write locked to get changed. If that is not the case for you, then my approach will not work. So if it sounds reasonable for you, then see the solution.public static void Lock(string path, Action<FileStream> action){ var autoResetEvent = new AutoResetEvent(false); while(true) { try { using (var file = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Write)) { action(file); break; } } catch (IOException) { var fileSystemWatcher = new FileSystemWatcher(Path.GetDirectoryName(path)) { EnableRaisingEvents = true }; fileSystemWatcher.Changed += (o, e) => { if(Path.GetFullPath(e.FullPath) == Path.GetFullPath(path)) { autoResetEvent.Set(); } }; autoResetEvent.WaitOne(); } }}
So as you can see, we do an infinite loop which exits only on nonIOException
or when the block finishes successfully.
To wait and not consume 100% CPUAutoResetEvent
which gets Set byFileSystemWatcher.Changed
event.
So the flow looks like that:
1) We try to open the file
2) If we have an IOException, we wait until the file gets changed
3) We try to open file again, if failed - wait again
4) If file opened successfully, we perform an action passed as a parameter
You should carefully handleIOException
inside your action. See the example:FileLocker.Lock(@"c:\file", (f) => { try { f.Write(buf, 0, buf.Length); } catch(IOException ioe) {// handle IOException } });
If you have any ideas on how to improve the solution, feel free to comment.
0 0
- C#多线程访问FileStream文件提示已打开
- C# FileStream 同时打开一个文件的方法
- C# FileStream文件读写
- microsoft 2003重新安装,或者打开文件提示临时文件夹已满或不能访问
- C# System.IO.FileStream 读取被其他程序打开的文件提示“文件正由另一进程使用,因此该进程无法访问该文件。”
- C# System.IO.FileStream 读取被其他程序打开的文件提示“文件正由另一进程使用,因此该进程无法访问该文件。”
- C# FileStream 文件读写(转)
- C# FileStream 文件读写(转)
- C# FileStream写文件解析
- C#使用FileStream文件读写
- c#的FileStream文件流
- C# FileStream流文件读写
- C# FileStream复制大文件
- C# FileStream复制大文件
- c# 使用FileStream打开并清空文件、将一文件内容另存为到新文件
- c# 使用FileStream打开并清空文件、将一文件内容另存为到新文件
- win7下excel提示“文件已损坏,无法打开。”解决办法
- C# System.IO.FileStream 读取文件提示“文件正由另一进程使用,因此该进程无法访问该文件。”
- listview点击无效怎么处理
- 资管后台selenium自动化测试说明
- elasticsearch配置mapping时,对所有的type有效
- 解决js页面传参到action中文乱码问题
- linux操作系统常用命令及常用问题
- C#多线程访问FileStream文件提示已打开
- Yii2里自定义函数的保存位置和使用方法
- Java配置环境变量
- struts2.5.2解决中文乱码
- Android开发,Http请求整合框架(新)基于Volley
- Python数据可视化:中心极限定律
- JavaScript正则表达式1
- [C/C++学习]之十二、++i 和 i++性能比较
- netcat: 高档货 linux中ftp和telnet的替代品