对于使用文件作为公司设备预订的某种全局存储的应用程序,我需要一种读取和写入文件的方法(或锁定文件、读取文件、写入文件和解锁文件)。一个小代码片段将说明我的意思:
FileStream in = new FileStream("storage.bin", FileMode.Open);
//read the file
in.Close();
//!!!!!
//here is the critical section since between reading and writing, there shouldnt
//be a way for another process to access and lock the file, but there is the chance
//because the in stream is closed
//!!!!!
FileStream out = new FileStream("storage.bin", FileMode.Create);
//write data to file
out.Close();
这应该得到这样的东西
LockFile("storage.bin");
//read from it...
//OVERwrite it....
UnlockFile("storage.bin");
该方法应该是绝对安全的,因为程序应该同时在 2000 台设备上运行