Showing posts with label ReadAllText. Show all posts
Showing posts with label ReadAllText. Show all posts

Friday, January 2, 2015

File.ReadAllText with an Offset in .NET

What do you do when you need to read text from a file in .NET, but you want to start from an offset? This is a slightly niche scenario, but it does happen. Below is a solution to that problem.

To summarize the implementation, you open a file stream, seek to your offset, and then read in the bytes from there. While loading the result I read small chunks into a buffer, decoded them, and then added the decoded string to a string buffer for storage. Please note that if you are using a multibyte encoding then this helper will only work if you use the correct offset.

Helper Code

public class FileHelper
{
    private const int BufferSize = 1024;
 
    public static string ReadAllTextFromOffset(
        string path, 
        Encoding encoding, 
        int offset, 
        out int totalLength)
    {
        using (var fs = new FileStream(path, FileMode.Open))
        {
            totalLength = offset;
 
            if (offset > 0)
            {
                fs.Seek(offset, SeekOrigin.Begin);
            }
 
            var sb = new StringBuilder();
            var buffer = new byte[BufferSize];
            int readCount;
 
            do
            {
                readCount = fs.Read(buffer, 0, buffer.Length);
                totalLength += readCount;
 
                var subString = encoding.GetString(buffer, 0, readCount);
                sb.Append(subString);
            }
            while (readCount == buffer.Length);
 
            return sb.ToString();
        }
    }
}
Real Time Web Analytics