如何使用C#锁定文件?

时间:2011-04-02 08:59:17

标签: c# io

我不确定人们通常通过“锁定”文件来表达什么意思,但我想要的是在我尝试打开的时候会对产生“指定文件正在使用”错误消息的文件执行此操作它与另一个应用程序。

我想这样做来测试我的应用程序,看看当我尝试打开处于此状态的文件时它的行为。我试过这个:

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 个答案:

答案 0 :(得分:36)

您需要传递FileShare枚举值None才能在FileStream constructor overloads上打开:

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

答案 1 :(得分:33)

根据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);

答案 2 :(得分:5)

虽然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. 

答案 3 :(得分:0)

我经常需要它来将它添加到我的 $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()
}