C# FileStream Lock
Description
FileStream Lock
Prevents other processes from reading
from or writing to the FileStream.
Syntax
FileStream.Lock
has the following syntax.
public virtual void Lock(
long position,
long length
)
Parameters
FileStream.Lock
has the following parameters.
position
- The beginning of the range to lock. The value of this parameter must be equal to or greater than zero (0).length
- The range to be locked.
Returns
FileStream.Lock
method returns
Example
The following code example demonstrates how to lock part of a file so another process cannot access that part of the file.
using System;/* w w w . jav a 2 s . c om*/
using System.IO;
using System.Text;
class FStreamLock
{
static void Main()
{
UnicodeEncoding uniEncoding = new UnicodeEncoding();
string myData = "from java2s.com ";
int textLength = uniEncoding.GetByteCount(myData);
int recordNumber = 13;
int byteCount = uniEncoding.GetByteCount(recordNumber.ToString());
using (FileStream fileStream = new FileStream("Test.dat", FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.ReadWrite))
{
fileStream.Lock(textLength - 1, byteCount);
Console.WriteLine("The specified part " +
"of file has been locked.");
fileStream.Unlock(
textLength - 1, byteCount);
Console.WriteLine("The specified part " +
"of file has been unlocked.");
}
}
}
The code above generates the following result.