How to lock a file with C#?
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 loc开发者_StackOverflow中文版kToolStripMenuItem_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?
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);
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.
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()
}
精彩评论