Recently I've faced with problem the I cannot share the file access between processes/threads. Simple code:
FileStream open = File.Open("path", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
Next calling if FileOpen with FileAccess.Read and sharing - None or Read - throws the exeption.
It must be assumed that this code allows reading for anyone the same as "native" WinAPI function CreateFile which works just perfect in this case.
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CreateFileW(
[MarshalAs(UnmanagedType.LPWStr)] string filename,
[MarshalAs(UnmanagedType.U4)] EFileAccess access,
[MarshalAs(UnmanagedType.U4)] EFileShare share,
IntPtr securityAttributes,
[MarshalAs(UnmanagedType.U4)] ECreationDisposition creationDisposition,
[MarshalAs(UnmanagedType.U4)] EFileAttributes flagsAndAttributes,
IntPtr templateFile);
IntPtr ptr = CreateFileW(path,
EFileAccess.GenericRead,
EFileShare.None,
IntPtr.Zero,
ECreationDisposition.OpenExisting,
EFileAttributes.Normal,
IntPtr.Zero);
So, is there any tricks to share file access using just .NET?
One more moment! Actually we are able to share the file with next code:
FileStream open = File.Open("path", FileMode.OpenOrCreate, **FileAccess.Read**, FileShare.Read);
But in my case - I do need that the first thread will be able to write file!!