Silvio Langereis
Silvio Langereis

Reputation: 471

Read/Write lock in c#

Our application needs to lock down a file to read-only when it is opened the first time. I have the code below, which doesn't seem to work anymore. Now, for some reason, it never triggers the exception when I open a second file and just passes through the first statement every time.

From what I understand, the logic behind this code is this: The first file opens the file with Read/Write (FileAccess.ReadWrite) and sets the file to Read for subsequent users (FileShare.Read).

When it is opened the second time, it will try and open it with Read/Write but is restricted to Read-Only upon which it triggers the exception and goes to the second statement. There it will open the file as Read-Only(FileAccess.Read) and set it back to read-write(FileAccess.ReadWrite) for subsequent users, this to ensure that the first document does not get locked out of its already permitted Write rights, which caused an exception.

I tested this already, it used to work with below code. I can still verify that the read-lock is set. When I open the file in another PDF editor, it cannot save, just read. When I do it in my own application, I can save whenever I want.

Am I missing something, or was there a fluke so that it temporarily worked ?

try
 {
    m_FileStream = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
    m_bCanWrite = true;
 }
 catch (Exception)
 {
    m_FileStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    m_bCanWrite = false;
 }

I changed the code so it uses using blocks, with the same params, but the result is also the same.

try
                {
                    FileInfo info = new FileInfo(fileName);
                    using (FileStream readWriteStream = info.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
                    {
                        m_bcanWrite = true;
                        m_PdfDocument = new PDFDoc(readWriteStream);
                    }

                }
                catch (Exception) 
                {
                    FileInfo info = new FileInfo(fileName);
                    using (FileStream readStream = info.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        m_bcanWrite = false;
                        m_PdfDocument = new PDFDoc(readStream);
                    }

                }

Upvotes: 1

Views: 820

Answers (1)

Evk
Evk

Reputation: 101583

As we figured out in comments - the reason was premature closing of the file stream. Of course when you close filestream - all locks on it are released. It's not a good idea to hold the file open for the duration of the whole application run time as you suggested in comment - just close the file when you are done with it, not sooner but not later.

Upvotes: 1

Related Questions