views:

533

answers:

3

C#: How do you specifiy where to start reading in a file when using StreamReader?

I have created a streamreader object, along with a file stream object. After both objects are created, how would I go upon controlling where I want the StreamReader to start reading from a file?

Let's say the file's contents are as follows,

// song list. // junk info. 1. Song Name 2. Song Name 3. Song Name 4. Song Name 5. Song Name 6. Song Name

How would I control the streamreader to read from let's say #2? Also, how could I also control where to make it stop reading by a similar delimiter like at #5?

Edit: By delimiter I mean, a way to make StreamReader start reading from ('2.')

+1  A: 

If the file contains new line delimiters you can use ReadLine to read a line at a time.

So to start reading at line #2, you would read the first line and discard and then read lines until line #5.

Mitch Wheat
A: 

Well if the content is just plain text like that, you should use the StreamReader's ReadLine method.

http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspx

-Oisin

x0n
+1  A: 

Are you trying to deserialize a file into some in-memory object? If so, you may want to simply parse the entire file in using ReadLine or something similar, store each line, and then access it via a data structure such as a KeyValuePair<int, string>.

Update: Ok... With the new info, I think you have two options. If you're looking at reading until you find a match, you can Peek(), check to see if the character is the one you're looking for, and then Read(). Alternatively, if you're looking for a set position, you can simply Read() that many characters and throw away the return value.

If you're looking for complex delimiter, you can read the entire line or even the entire file into memory and use Regular Expressions.

Hope that helps...

Andrew Flanagan