When using a file stream, and setting FileShare
to None
, and say two users accessing the same function at the same time want to read/write to that file. Will FileShare.None
make the second users request waiting or will the second user's request throw an exception?
//two users get to this this code at the same time
using (FileStream filestream = new FileStream(chosenFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
using (StreamReader sr = new StreamReader(filestream))
using (StreamWriter sw = new StreamWriter(filestream))
{
//reading and writing to file
}
Msdn says: None Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.
But will requests keep trying until the filestream is closed?
When a process opean a file for Read/Write with
FileShare.None
any subsequent access by any process on this same file will result inAcess Denied Exception
. To answer your question, Second user will get exception.There are many ways you can handle these kind of concurrent file access issues, Following code demonstrates a simple approach to tackle this situation.