如何用C#锁定文件?

42

我不确定人们通常所说的“锁定”文件是指什么,但我想要的是对文件进行处理,以便在尝试使用另一个应用程序打开它时会产生“指定的文件正在使用”错误消息。

我想这样做是为了测试我的应用程序,看看当我尝试打开处于此状态的文件时它会如何表现。我尝试了以下方法:

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();
}

但显然它没有做我期望的事情,因为我可以在“锁定”文件时使用记事本打开它。那么,为了进行测试,如何锁定一个文件以使其无法被其他应用程序打开?

4个回答

62

要打开FileStream构造函数重载,您需要传递一个值为NoneFileShare枚举值:

fs = new FileStream(@"C:\Users\Juan Luis\Desktop\corte.txt", FileMode.Open, 
    FileAccess.ReadWrite, FileShare.None);

41
希望我有时可以接受两个答案,因为它们几乎完全相同。希望你不介意我选择另一个人,因为他的得分较低 :) - Juan

56

1
注意:在Windows上,在文件上打开FileStream可以完美地起到锁定的作用,但在Linux上似乎没有任何效果。 - Shukri Adams

9

虽然FileShare.None无疑是锁定整个文件的快速简便解决方案,但您也可以使用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. 

反过来,您可以使用以下方法解锁文件: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. 

-1

我需要经常使用它,因此将其添加到我的$PROFILE中以便从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()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接