开发者

Why is FileShare.ReadWrite not working in this scenario?

开发者 https://www.devze.com 2023-04-04 01:51 出处:网络
I have the need to open up a single file in two different instances of a process. The two ways that I open up the file (both within each process) are as follows:

I have the need to open up a single file in two different instances of a process. The two ways that I open up the file (both within each process) are as follows:

m_Stream = new FileStream(name, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite,4*1024,FileOptions.WriteThrough);

and

            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern SafeFileHandle CreateFile(
            string fileName,
            [MarshalAs(UnmanagedType.U4)] FileAccess fileAccess,
            [MarshalAs(UnmanagedType.U4)] FileShare fileShare,
            IntPtr securityAttributes,
            [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
            int flags,
            IntPtr template);

m_Stream = new FileStream(                                                                                    //no buffering
                        CreateFile(name, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, 0x20000000, IntP开发者_开发问答tr.Zero),
                        FileAccess.ReadWrite);

Now I realize this is a very specialized scenario with both the interop call and the FileOptions.WriteThrough. However, FileShare.ReadWrite does not seem to be working. The second process (using the same code) that tries to access the file gets the usual another process is accessing this file exception. Within the same process, seems to work fine for sharing. Any thoughts?


Not sure how you concluded this. The pinvoke declaration is bad, the 2nd argument to CreateFile is not compatible with FileAccess. It requires a combination of GENERIC_READ (0x8000000) and GENERIC_WRITE (0x40000000). FileShare actually is compatible with the winapi flags. Your best bet to get this right is to use Reflector or ILSpy or the Reference Source and look at the code for FileStream.Init(). It does the mapping between FileStream constructor and CreateFile argument values.

0

精彩评论

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