Tracking File position in C#

  • Thread starter Thread starter Senthil
  • Start date Start date
S

Senthil

Hi,
The need is to read each line in a text file and based on the read
data decision has to be taken whether to reposition the file pointer. The
StreamReader.Position does not give current position. But it gives position
in multiples of 1024. Also, I am not finding a way to reposition the pointer
using FileStream-StreamReader combination. Due to this the condition
(FileLength = = File Position) misbehaves.
I did some investigation and found out only when i use Read method the file
pointer position gets updated after each read operation. Is there any way by
using the StreamReader-FileStream combination can it be done?
How could such file pointer reposition and tracking file pointer position
could be done elegantly in C# ?

Can anyone help?
Thanks,
Senthil

C# code:
 
You can use FileStream Seek method

From the doc: "Sets the current position of this stream to the given value."

here is an expample

const string fileName = "Test#@@#.dat";

// Create random data to write to the file.
byte[] dataArray = new byte[100000];
new Random().NextBytes(dataArray);

using(FileStream
fileStream = new FileStream(fileName, FileMode.Create))
{
// Write the data to the file, byte by byte.
for(int i = 0; i < dataArray.Length; i++)
{
fileStream.WriteByte(dataArray);
}

// Set the stream position to the beginning of the file.
fileStream.Seek(0, SeekOrigin.Begin);

// Read and verify the data.
for(int i = 0; i < fileStream.Length; i++)
{
if(dataArray != fileStream.ReadByte())
{
Console.WriteLine("Error writing data.");
return;
}
}
Console.WriteLine("The data was written to {0} " +
"and verified.", fileStream.Name);
}
 
Senthil said:
The need is to read each line in a text file and based on the read
data decision has to be taken whether to reposition the file pointer. The
StreamReader.Position does not give current position. But it gives position
in multiples of 1024. Also, I am not finding a way to reposition the pointer
using FileStream-StreamReader combination. Due to this the condition
(FileLength = = File Position) misbehaves.
I did some investigation and found out only when i use Read method the file
pointer position gets updated after each read operation. Is there any way by
using the StreamReader-FileStream combination can it be done?
How could such file pointer reposition and tracking file pointer position
could be done elegantly in C# ?

Well, if it's a simple encoding (eg ISO-8859-1, or ASCII) you could
assume a byte per character, and increment your own counter.

Note that if you reposition the stream, you should call
StreamWriter.DiscardBufferedData().
 
Back
Top