2

I'm doing the following:

var streamWriter = new FileStream("foo.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);

Thus, I want to open foo.bin (or create it if it does't exist); I want to read and write to it from streamWriter, and I want others to be able to open it for reading. But when I subsequently do this:

var streamReader = File.OpenRead("foo.bin");

I get the exception The process cannot access the file 'foo.bin' because it is being used by another process.

What gives? I did want others to be able to open it for reading...

HelloWorld
  • 3,381
  • 5
  • 32
  • 58

2 Answers2

3

This is because File.OpenRead is the same as FileStream reader = new FileStream("file", FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read); and a prior FileStream has it opened for reading and writing. As such the fileshare on it will fail. Try this instead of File.OpenRead()

FileStream reader = new FileStream("File", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);

Heres a link to the documentation on File.OpenRead https://learn.microsoft.com/en-us/dotnet/api/system.io.file.openread?view=net-5.0

Ben
  • 757
  • 4
  • 14
  • I'm not sure I understand this. When the file is first created, it says that anybody can access it (FileShare.Read), i.e. to read from the file. But the only way to open it without getting an exception is to ask for read/write (FileShare.ReadWrite) permissions? It does work though :) – HelloWorld Dec 16 '20 at 14:11
  • in the first stream you are opening it and allowing that stream to read and write from it and others to only read from it. The second stream is allowing itself to only read but others to read and write from it. I'm running a quick test to see if this applies even if its in 2 different processes, or if its just a quirk. – Ben Dec 16 '20 at 15:45
  • Yea it holds across processes. I assume its because the second stream cant set the file share to be Read only because it is already opened for reading and writing by the previous. – Ben Dec 16 '20 at 15:52
0

this link is good to start [blog]: https://csharp.net-tutorials.com/file-handling/reading-and-writing/ "click here for solution"

for same stream:: [blog]: Read and write to a file in the same stream "click here for solution