【问题标题】:How to lock a file with C#?如何使用 C# 锁定文件?
【发布时间】:2011-07-28 04:36:31
【问题描述】:

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

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

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

但显然它没有达到我的预期,因为我能够在“锁定”时用记事本打开文件。那么如何锁定一个文件,使其不能被其他应用程序打开以进行测试呢?

【问题讨论】:

    标签: c# io


    【解决方案1】:

    您需要传入NoneFileShare 枚举值才能在FileStream constructor overloads 上打开:

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

    【讨论】:

    • 希望我有时可以接受这两个答案,因为它们几乎完全相同。希望你不介意我接受另一个人,因为他的分数较低:)
    【解决方案2】:

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

    【讨论】:

    • 注意:在文件上打开 FileStream 可以完美地作为 Windows 中的锁,但在 Linux 中似乎没有任何效果。
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-09
        • 1970-01-01
        • 1970-01-01
        • 2014-11-09
        • 2011-11-26
        • 1970-01-01
        • 1970-01-01
        • 2021-09-08
        相关资源
        最近更新 更多