Locking issues with replacing files on a website
Posted
by Moe Sisko
on Stack Overflow
See other posts from Stack Overflow
or by Moe Sisko
Published on 2009-12-02T00:07:55Z
Indexed on
2010/04/05
11:43 UTC
Read the original article
Hit count: 418
I want to replace existing files on an IIS website with updated versions. Say these files are large pdf documents, which can be accessed via hyperlinks. The site is up 24x7, so I'm concerned about locking issues when a file is being updated at exactly the same time that someone is trying to read the file.
The files are updated using C# code run on the server. I can think of two options for opening the file for writing.
Option 1) Open the file for writing, using FileShare.Read :
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
While this file is open, and a user requests the same file for reading in a web browser via a hyperlink, the document opens up as a blank page.
Option 2) Open the file for writing using FileShare.None :
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
While this file is open, and a user requests the same file for reading in a web browser via a hyperlink, the browser shows an error. In IE 8, you get HTTP 500, "The website cannot display the page", and in Firefox 3.5, you get : "The process cannot access the file because it is being used by another process."
The browser behaviour kind of makes sense, and seem reasonable. I guess its highly unlikely that a user will attempt to read a file at exactly the same time you are updating it. It would be nice if somehow, the file update was atomic, like updating a database with SQL wrapped around a transaction.
I'm wondering if you guys worry about this sort of thing, and prefer either of the above options, or even have other options of your own for updating files.
© Stack Overflow or respective owner