How to lock a file with C#?

后端 未结 3 740
庸人自扰
庸人自扰 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:04

    You need to pass in a FileShare enumeration value of None to open on the FileStream constructor overloads:

    fs = new FileStream(@"C:\Users\Juan Luis\Desktop\corte.txt", FileMode.Open, 
        FileAccess.ReadWrite, FileShare.None);
    
    0 讨论(0)
  • 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. 
    
    0 讨论(0)
  • 2020-11-29 07:15

    As per 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);
    
    0 讨论(0)
提交回复
热议问题