A FileStream will let you search for the part of the file you want without problems. This is the recommended way to do this in C #, and it is fast.
Exchange between threads: you need to create a lock so that other threads do not change the position of the FileStream while you are trying to read it. The easiest way to do this:
// This really needs to be a member-level variable; private static readonly object fsLock = new object(); // Instantiate this in a static constructor or initialize() method private static FileStream fs = new FileStream("myFile.txt", FileMode.Open); public string ReadFile(int fileOffset) { byte[] buffer = new byte[bufferSize]; int arrayOffset = 0; lock (fsLock) { fs.Seek(fileOffset, SeekOrigin.Begin); int numBytesRead = fs.Read(bytes, arrayOffset , bufferSize); // Typically used if you're in a loop, reading blocks at a time arrayOffset += numBytesRead; } // Do what you want to the byte array and return it }
If necessary, add try..catch and other code. Everywhere you access this file stream, put a lock on a member level fsLock level variable ... this will allow other methods to read / manipulate the file pointer while reading.
Most likely, I think you will find that you are limited by the speed of access to the disk, not the code.
You will have to think about all the problems associated with multi-threaded file access ... who initializes / opens the file, which closes it, etc. There is a lot of space to cover.
source share