Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lock a file with C#?

Tags:

c#

io

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?

like image 217
Juan Avatar asked Apr 02 '11 08:04

Juan


People also ask

How do I lock a file in CS?

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.

What is write lock for a 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.

How do I lock a file for editing?

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.

How do I lock a file in NFS?

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.


2 Answers

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); 
like image 200
Richard Szalay Avatar answered Oct 05 '22 01:10

Richard Szalay


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); 
like image 26
BugFinder Avatar answered Oct 05 '22 02:10

BugFinder