Limiting the number of concurrent users for c# program using a lock-file

Viewed 73

I have made a C# program, and i want to limit the number of concurrent users, for licensing reasons.

The program itself (the exe-file) is installed locally, and the datafiles (not a database) is stored on a shared drive on the server.

My idea was to have a lock-file, that each instance of the program would keep a ReadWrite handle to.

And then I would count the open file handles to the lock-file. When the number of handles would reach 5, i would reject more handles, and not allow the program to start,

Something like:

FileStream fileStream = new FileStream(@"f:\blabla\lock.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);

if (filestream.CountFileHandles()>5) return false; 

But i can't figure out how to count the open files handles to the lock-file.

I don't want to write anything in the lock-file. Just count the handles.

Or maybe I am following a wrong path, and somebody can guide me to a better solution, how to limit the number of concurrent users.

1 Answers

It is dirty but this might just work......

You make up front as many lock files as you are going to allow concurrent users. So if you allow 10 users then it will be:

f:\blabla\lock0.txt, f:\blabla\lock1.txt, ....., f:\blabla\lock9.txt

To obtain a 'license' the program iterates through all the files, attempting to read each one in exclusive mode eg:

File.open(f, FileMode.Open, FileAccess.ReadWrite, FileShare.None)

Keep trying 0..9 until either this succeeds for one of the files (in which case you now have your license) or else you tried them all (in which case you did not get one)

Make it work as well as possible by cleanly closing the file whenever you exit the program.

Ultimately, there are always issues with home rolled license solutions. If it is more than a handful of concurrent users, some kind of server solution would be better, probably one you did not write yourself.

Related