Skip to main content

C# example showing how to read a file simultaneously from different threads without having any locks.

// Reading a file without locking it

byte[] oFileBytes = null;
string myFile = "TalkDotNet.txt";

using(System.IO.FileStream fs = System.IO.File.Open(
    myFile,
    System.IO.FileMode.Open,
    System.IO.FileAccess.Read,
    System.IO.FileShare.ReadWrite))
{
    int numBytesToRead = Convert.ToInt32(fs.Length);
    oFileBytes = new byte[(numBytesToRead)];
    fs.Read(oFileBytes, 0, numBytesToRead);
}