38

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?

Branislav Abadjimarinov
  • 5,061
  • 3
  • 37
  • 44
Juan
  • 14,840
  • 23
  • 98
  • 182

4 Answers4

57

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);
Richard Szalay
  • 81,010
  • 19
  • 172
  • 232
  • 39
    Wish I can sometimes accept both answers as they are pretty much exactly the same. Hope you don't mind I'm accepting the other guy because of his lower score :) – Juan Apr 02 '11 at 09:23
52

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);
BugFinder
  • 16,714
  • 4
  • 38
  • 50
  • Note : opening a FileStream on a file works perfectly as a lock in Windows, but does not appear to have any effect in Linux. – Shukri Adams Aug 02 '21 at 20:38
10

While FileShare.None is undoubtedly a quick and easy solution for locking a whole file you could lock part of a file using FileStream.Lock()

public virtual void Lock(
    long position,
    long length
)

Parameters

position
    Type: System.Int64
    The beginning of the range to lock. The value of this parameter must be equal to or greater than zero (0). 

length
    Type: System.Int64
    The range to be locked. 

and conversely you could use the following to unlock a file: FileStream.Unlock()

public virtual void Unlock(
    long position,
    long length
)

Parameters

position
    Type: System.Int64
    The beginning of the range to unlock. 

length
    Type: System.Int64
    The range to be unlocked. 
Paul Zahra
  • 9,183
  • 7
  • 51
  • 72
0

I've needed this frequently enough to add this to my $PROFILE to use from PowerShell:

function Lock-File
{
    Param( 
        [Parameter(Mandatory)]
        [string]$FileName
    )

    # Open the file in read only mode, without sharing (I.e., locked as requested)
    $file = [System.IO.File]::Open($FileName, 'Open', 'Read', 'None')

    # Wait in the above (file locked) state until the user presses a key
    Read-Host "Press Return to continue"

    # Close the file (This releases the current handle and unlocks the file)
    $file.Close()
}
Glenn
  • 1,469
  • 13
  • 20