How to put a lock on a file in a multi user environment?
I have an executable which is hosted on a server and can be launched from several client work stations. The exe needs to read and write to a particular text file that is located on the same server(shared location). Since the exe can b开发者_如何学Ce launched from multiple work stations, I need to put a lock on the text file and do some processing and unlock the file so at any time, only one user will be able to access the file. Also, I need to display some message to the user when the file is locked by another user. Once the file is unlocked, it should be available for the other user to lock and do the processing.
Is there anybody who can provide some sample code snippet how to achieve this? Thanks a lot for any help.
You need to open the file with Write access and with FileShare.None
, which means it's not able to be written to by anyone else while the user has it open.
The try..catch...
block will enable you to give them a message telling them the file is unavailable.
FileInfo file = new FileInfo(@"YourfileLocationAndFileName");
try
{
using(FileStream fileStream1 = file.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
//Use the filestream to do your readwrite here.
}
}
catch(IOException ex)
{
//pop up message box here to inform the user the file is currently in use
}
Try opening the file with FileShare.None
using this ctor.
The mutex/semaphore technique for serializing access to a shared resource is slightly more involved but you can find many examples and explanations by doing a web search. This technique will allow you to wait for the file to become available, control access to any granularity you need .
Basically when a writer wishes to lock the file, they must first acquire a mutex, which is an exclusive synchronization object. If another writer has the mutex, the second requester can wait for it. If you want to also allow read only access, you can add semaphores. Each reader acquires a semaphore to indicate they are reading the file. Then when a writer acquires a mutex they must also wait for each reader to finish, as signaled by the semaphores.
It is not difficult to implement but more than I can show example code for. As I say you can find many tutorials and examples on the web.
精彩评论