zoukankan      html  css  js  c++  java
  • FileStream:The process cannot access the file because it is being used by another process

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

                    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 GetLastError function would return ERROR_SHARING_VIOLATION.

  • 相关阅读:
    Nginx 本地建立负载均衡(Windows环境)
    Nginx 代理本地文件夹(Windows环境)
    PostGIS 使用Mysql_fdw同步ArcGIS填坑记录
    PostGIS mysql_fdw操作日志(留观)
    PostGIS mysql_fdw使用(Linux)
    PostGIS mysql_fdw安装(Linux)
    PostGIS 安装教程(Linux)(二)
    PostGIS 安装教程(Linux)(一)
    Linux 命令记录
    PostGIS 查看表属性(字段、类型、是否为空)
  • 原文地址:https://www.cnblogs.com/mschen/p/5353862.html
Copyright © 2011-2022 走看看