Finding a StreamReader's true position

G

Guest

I'm using a StreamReader to read in several lines from an ASCII file. I'd
like to know the StreamReader's "true" position-- that is, the number of
bytes into the file that the StreamReader has read. I thought about using
MyStreamReader.BaseStream.Position, but this always seems to return a
multiple of the StreamReader's buffer size (which seems natural-- as I
understand it the StreamReader reads from the underlying stream in discrete
blocks corresponding to the buffer size). I also considered counting the
bytes myself (as I read into the file), but ReadLine() doesn't record whether
the returned line ended in a CR, an LR, or both.

Any ideas?

Thanks,
Keith Kingsley
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

You can't using Streamreader for the same reason you expose. the solution
may be using a stream that does gives you the Position and then decorate it
with streamreader to have the "line" functionality.

Use a FileStream to open the file and them create a streamreader around it.
you could use FileStream.Position to know the position.

Even so, this may not be the solution, as the FileStream.Position will give
you what streamreader has readed, not what you consume.
Try it, if it does not work. you have to implement it . I think I have such
a code, I used it for a PPC application to read from a networkstream and
have a ReadString () like method. let me know if you need the code


cheers,
 
I

Ignacio Machin \( .NET/ C# MVP \)

Here is the code


public string ReadStringFromNetwork( )
{
StringBuilder buff;
try
{
buff = new StringBuilder( 20);
int ch;
while( (ch=networkstream.ReadByte())!= -1)
{
if (ch == 13) continue;
if ( ch==10) return buff.ToString();
buff.Append( Convert.ToChar( ch));

}
}
catch(Exception e)
{
throw new Exception("\n==>Method: NetAccess.ReadStringFromNetwork,
reading string :" + e.Message );

}
return buff.ToString();
}


PLEASE NOTE:
the code above assume that each character is 1 byte long, this is not true
with unicode so you have to be careful with this.


cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top