FileStream Cannot Access File Because Used by Another Process

Published on Tuesday, July 5, 2011

We have a FileStream code using new FileStream:

using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))   
{    
…    
}

However, we sometimes got the file share kind errors such as “The process cannot access the file … because it is being used by another process.”

IOExcp00

We searched help information. some cases used the following solution:

using (FileStream fs = 
    new FileStream(filePath,
        FileMode.Open, FileAccess.Read, FileShare.ReadWrite))

Explain from MSDN:

ReadWrite: 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. However, even if this flag is specified, additional permissions might still be needed to access the file.