Search code examples
c#streamreader

Read textfile from specific position till specific length


Due to me receiving a very bad datafile, I have to come up with code to read from a non delimited textfile from a specific starting position and a specific length to buildup a workable dataset. The textfile is not delimited in any way, but I do have the starting and ending position of each string that I need to read. I've come up with this code, but I'm getting an error and can't figure out why, because if I replace the 395 with a 0 it works..

e.g. Invoice number starting position = 395, ending position = 414, length = 20

using (StreamReader sr = new StreamReader(@"\\t.txt"))
{                    
    char[] c = null;                   
    while (sr.Peek() >= 0)
    {
        c = new char[20];//Invoice number string
        sr.Read(c, 395, c.Length); //THIS IS GIVING ME AN ERROR                      
        Debug.WriteLine(""+c[0] + c[1] + c[2] + c[3] + c[4]..c[20]);
    }
}

Here is the error that I get:

System.ArgumentException: Offset and length were out of bounds for the array 
                          or count is greater than the number of elements from
                          index to the end of the source collection. at
                          System.IO.StreamReader.Read(Char[] b

Solution

  • 395 is the index in c array at which you start writing. There's no 395 index there, max is 19. I would suggest something like this.

    StreamReader r;
    ...
    string allFile = r.ReadToEnd();
    int offset = 395;
    int length = 20;
    

    And then use

    allFile.Substring(offset, length)