开发者

FileShare ReadWrite not working (C#.NET)

I'm using a hex-editor control for C#, the source code and binary files can be found here.

One problem when using it was that if a file was loaded in the hex-editor and another program, the other program can't save the file, because it's already being used by another process.

So I asked the author of the control who told me to set the FileShare argument in the File.Open method in the FileByteProvider and DynamicFileByteProvider class to ReadWrite (it was originally only Read) would fix it. So I did that, but it still didn'开发者_如何学JAVAt work (same error). Setting it to Write only also didn't work, but setting it to Read only and None both work. The files have the same problem in any program, for example Notepad. They aren't set to ReadOnly or anything, so I have no idea why it doesn't work.

Is there anything I am missing here?


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜