'How to read a file starting at a specific cursor point in C#?

I want to read a file but not from the beginning of the file but at a specific point of a file. For example I want to read a file after 977 characters after the beginning of the file, and then read the next 200 characters at once. Thanks.



Solution 1:[1]

you can use Linq and converting array of char to string .

add these namespace :

using System.Linq;
using System.IO;

then you can use this to get an array of characters starting index a as much as b characters from your text file :

char[] c = File.ReadAllText(FilePath).ToCharArray().Skip(a).Take(b).ToArray();

Then you can have a string , includes continuous chars of c :

string r = new string(c);

for example , i have this text in a file :

hello how are you ?

i use this code :

char[] c = File.ReadAllText(FilePath).ToCharArray().Skip(6).Take(3).ToArray();               
string r = new string(c);
MessageBox.Show(r);

and it shows : how

Way 2

Very simple : Using Substring method

string s = File.ReadAllText(FilePath);
string r = s.Substring(6,3);
MessageBox.Show(r);

Good Luck ;

Solution 2:[2]

using (var fileStream = System.IO.File.OpenRead(path))
{
    // seek to starting point
    fileStream.Position = 977;

    // read
}

Solution 3:[3]

if you want to read specific data types from files System.IO.BinaryReader is the best choice. if you are not sure about file encoding use

        using (var binaryreader = new BinaryReader(File.OpenRead(path)))
        {
            // seek to starting point
            binaryreader.ReadChars(977);
            // read
            char[] data = binaryreader.ReadChars(200);
            //do what you want with data
        }

else if you know character size in source file size are 1 or 2 byte use

        using (var binaryreader = new BinaryReader(File.OpenRead(path)))
        {
            // seek to starting point
            binaryreader.BaseStream.Position = 977 * X;//x is 1 or 2 base on character size in sourcefile
            // read
            char[] data = binaryreader.ReadChars(200);
            //do what you want with data
        }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Aliostad
Solution 3