I'm not sure what people usually mean by "lock" a file, but what I want is to do that thing to a file that will produce a "The specified file is in use" error message when I try to open it with another application.
I want to do this to test my application to see how it behaves when I try to open a file that is on this state. I tried this:
FileStream fs = null; private void lockToolStripMenuItem_Click(object sender, EventArgs e) { fs = new FileStream(@"C:\Users\Juan Luis\Desktop\corte.txt", FileMode.Open); } private void unlockToolStripMenuItem_Click(object sender, EventArgs e) { fs.Close(); }
But apparently it didn't do what I expected because I was able to open the file with Notepad while it was "locked". So how can I lock a file so it cannot be opened with another application for my testing purposes?
Lock a file while Reading/Writing the file data – Approach 2 Lock a file in C# using File. Lock() method . The lock method let you lock a file so another process cannot access the file. This works even if it has read/write access to the file.
An exclusive or write lock gives a process exclusive access for writing to the specified part of the file. While a write lock is in place, no other process can lock that part of the file. A shared or read lock prohibits any other process from requesting a write lock on the specified part of the file.
Right-click a file (or click the ellipses (...)) to open the More Options menu. Click Lock. Choose a duration for the lock. If you choose unlimited, the file will be locked until you unlock it manually.
With the NFS version 4 protocol, a client user can choose to lock the entire file, or a byte range within a file. z/OS NFS client file locking requests can be managed with the llock(Y|N) parameter on the mount command or as an installation default. z/OS NFS supports only advisory locking.
You need to pass in a FileShare
enumeration value of None
to open on the FileStream
constructor overloads:
fs = new FileStream(@"C:\Users\Juan Luis\Desktop\corte.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.None);
As per http://msdn.microsoft.com/en-us/library/system.io.fileshare(v=vs.71).aspx
FileStream s2 = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.None);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With