How to lock a file with C#?

后端 未结 3 763
庸人自扰
庸人自扰 2020-11-29 06:36

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 w

3条回答
  •  情话喂你
    2020-11-29 07:13

    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. 
    

提交回复
热议问题