如何用C#锁定文件?

如何用C#锁定文件?,c#,io,C#,Io,我不确定人们通常所说的“锁定”文件是什么意思,但我想对一个文件执行该操作,当我试图用另一个应用程序打开它时,该文件将产生“指定的文件正在使用”错误消息 我想这样做是为了测试我的应用程序,看看当我试图打开一个处于这种状态的文件时它是如何工作的。我试过这个: FileStream fs = null; private void lockToolStripMenuItem_Click(object sender, EventArgs e) { fs = new FileStream(@"C:

我不确定人们通常所说的“锁定”文件是什么意思,但我想对一个文件执行该操作,当我试图用另一个应用程序打开它时,该文件将产生“指定的文件正在使用”错误消息

我想这样做是为了测试我的应用程序,看看当我试图打开一个处于这种状态的文件时它是如何工作的。我试过这个:

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();
}
但显然它没有达到我预期的效果,因为我可以在文件被“锁定”时用记事本打开文件。因此,如何锁定文件,使其无法使用其他应用程序打开以进行测试?

您需要传入枚举值
None
,才能在以下位置打开:

依照


而FileShare.None无疑是锁定整个文件的一个快速而简单的解决方案,您可以使用

相反,您可以使用以下方法解锁文件:


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

但愿我有时能接受这两个答案,因为它们几乎完全相同。希望你不介意我接受另一个人,因为他的分数较低:)
FileStream s2 = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.None);
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. 
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. 
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()
}