Sharing and Locking Files
BlitzPlus Forums/BlitzPlus Programming/Sharing and Locking Files
| ||
I am developing an application that will allow a user to load an external file, modify it, and then save the file back again. More than one user will be able to access the program. How can I lock out the file when one person is editing it in order that errors don't occur if two people run the program at the same time - ideally, it would be something similar to the thing you get in a Microsoft Office application i.e. "This document is being edited by A.N. Other. Do you want to open a read-only copy?" Thanks, Paul |
| ||
Why not just create a lock file when the app opens it. Check for the presence of that file and alert if it's there? The file could then also contain the details of the user who has the file open. |
| ||
That is just ace - many thanks, RiK. For the benefit of anyone else interested, here is what I did based on RiKs' suggestion. At the start of my app I have this.... ;--------------------------------------------------------------------------------------- ;Before we do anything, we are going to check if another user ;is already using the program. To do this, we check for the ;presence of a file called "lockfile.lck". If this file doesn't exist ;when the program is first run, the program will create it and ;execution continues. If it does exist, the program must already ;be running so it displays an error message and then exits. ;Under normal operation, the file "lockfile.lck" is deleted by ;the program as it ends. Global filename$ = "lockfile.lck" If FileType(filename$) Then Notify "This program is being used by another user.",True Goto Finished EndIf fileout = WriteFile(filename$) WriteString(fileout,"The program is now locked") CloseFile(fileout) and then at the end, this: ;delete the lockfile we created earlier filename$ = "lockfile.lck" If FileType(filename$) Then ;make sure that it does exist! DeleteFile "lockfile.lck" EndIf .Finished End Works a treat :-) |
| ||
Just an addition to your code - you might want to make sure that the FileType is actually a file, rather than a folder. |
| ||
Noted - thanks. Thus, change:If Filetype(filename$) then to: If Filetype(filename$) = 1 then It is also worth noting, for anyone who might want to use this, that something needs to be done if the program crashes for some reason having already created the lockfile. That's not a big issue, however. |
| ||
What you could do, is make the 'owner' update the lockfile every 60 seconds or so. When a new user comes along, they can only log in if the lockfile isn't there, or if the lockfile is present AND hasn't been updated in over 60 seconds. |