博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
FileStream:The process cannot access the file because it is being used by another process
阅读量:4692 次
发布时间:2019-06-09

本文共 1083 字,大约阅读时间需要 3 分钟。

先看下面一段代码(先以共享的方式打开文件读写,然后以只读的方式打开相同文件):

                FileStream fs  = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);

                FileStream fs2 = new FileStream(filePath, FileMode.Open, FileAccess.Read) 或者 new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

     第一句成功执行,第二句呢?它抛出访问违规异常:The process cannot access the file 'c:\Odma32.log' because it is being used by another process!

     查阅MSDN,无果。后经多次实验,包括使用Windows API CreateFile(...),最终发现正确的用法居然是:

                FileStream fs  = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);

                FileStream fs2 = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

     在打开fs2时,它必须制定FileShare为ReadWrite,因为fs以ReadWrite的方式打开的。

     结论:FileShare不只是对随后的打开文件请求有影响,但事实是它对已经打开的文件句柄也有影响。MSDN中关于FileShare的解释不到位,应该CreateFile条目中的这一段也放进去:

You cannot request a sharing mode that conflicts with the access mode that is specified in an existing request that has an open handle. CreateFile would fail and the  function would return ERROR_SHARING_VIOLATION.

转载于:https://www.cnblogs.com/mschen/p/5353862.html

你可能感兴趣的文章
Redis启停脚本
查看>>
RabbitMQ命令行手动创建队列rabbitmqadmin用法
查看>>
linux修改当前用户环境变量永久生效
查看>>
Javascript Asynchronous Investigation
查看>>
创建.net framework webapi出现“Web 服务器被配置为不列出此目录的内容。”错误
查看>>
c#中关于@的作用
查看>>
Excel转换成xml文件
查看>>
关于Java链接c#的webapi的注意事项
查看>>
关于vs无法创建虚拟目录的问题
查看>>
ad域的那些事儿
查看>>
如何将自己写的程序加入到计算机服务里
查看>>
C# 二维码 ThoughtWorks.QRCode.dll
查看>>
(转)C#使用itextsharp生成PDF文件
查看>>
EventBus
查看>>
简单的加减器
查看>>
Redis从基础命令到实战之集合类型(Set)
查看>>
test
查看>>
[py]python多态-动态语言的鸭子类型
查看>>
百练6183-人民币支付-2014正式A题
查看>>
C# 文件上传下载功能实现 文件管理引擎开发
查看>>