FileShare ReadWrite not working (C#.NET)

戏子无情 提交于 2019-12-02 02:48:29

The problem might be with the other program - if it's trying to open the file for exclusive access (with no sharing), it doesn't matter how your program has opened the file - it's going to fail.


Whenever a program tries to open a file, you specify a FileAccess and FileShare parameter (or defaults are taken if they're not explicitly passed).

What Windows then has to do is check all existing open file handles, and determine whether they're compatible. So it compares your FileAccess parameter against everyone else's FileShare parameters - are you allowed to do what everyone else has said they're happy for others to do? And then it performs the opposite check - does your FileShare parameter match up with their FileAccess parameters? - are they doing things that you're happy for them to be doing? Only if both checks pass can your particular open request be approved.

You can use something like Process Monitor to actually watch the Win32 calls being issued to CreateFile to see what each process is actually doing.


Notepad can open a file that's been shared for Read/Write, but it can't write back to the file. Sample program:

using System.IO;

namespace ConsoleApplication2
{
    class Program
    {

        static void Main(string[] args)
        {
            var fs = new FileStream(@"C:\Bar.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            fs.Write(System.Text.Encoding.ASCII.GetBytes("abc"),0,3);
            fs.Flush();
            fs.Close(); //<-- Breakpoint here
        }
    }
}

Set the given breakpoint, run the program. When it hits the breakpoint, open Notepad, and use it to open C:\Bar.txt. Everything is fine. Add more text to the file and hit save. You'll get an error message.

  1. Change to ReadWrite.
  2. Recompile.
  3. Try opening a file that you haven't tried opening yet and check if the problem appears.

Possibly, you weren't closing the file appropriately so it remained open even after you closed your application (with previous permissions set to Read)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!