How to lock a file with C#?

Solution 1:

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

Solution 2:

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

Solution 3:

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.