Search code examples
c#ioexception

File.Create and File.OpenRead and IOException


I need to read a file that is opened for writing in other part of the program

const string fileName = "file.bin";
FileStream create = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.Read);
FileStream openRead = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);

The last line raises IOException:

"The process cannot access the file because it is being used by another process"

Please help properly configure File.Open parameters.


Solution

  • Change FileShare parameter to FileShare.ReadWrite in both statement:

    FileStream create = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
    FileStream openRead = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    

    ReadWrite flag description from MSDN:

    Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed.