Click here to Skip to main content
14,695,406 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When by Using the Stream Reader if we read the File Line By Line.

Now If I wants to Write The File using StreamWriter At Some Specific Position Then How I will Come to Know about That When I was Present at that Specific Position.

Can Anyone Please Share The Explanation with an Example/Code Snippet ..?

1 solution

You can use the Seek method of the BaseStream property of StreamWriter class to jump to the location.

sample code
FileStream stream = new FileStream(@"filename.txt",FileMode.Open,FileAccess.ReadWrite);
StreamWriter writer = new StreamWriter(stream);

writer.BaseStream.Seek(10000, SeekOrigin.Begin); // where 10000 is the offset to jump
writer.WriteLine("new Test starts here");

Check MSDN-Seek[^] and BaseStream[^] links for more details
Sergey Alexandrovich Kryukov 17-Jan-13 16:56pm
Correct, a 5.
Jibesh 17-Jan-13 16:58pm
Thank you SA
AyushJain1890 23-Jan-13 13:32pm
Also The Small Addition to the above code.

You Need To Close The writer because The Data is in the RAM before closing the writer, Once the writer is closed the data is written in the file as the Data is Transferred from RAM to main memory
Jibesh 23-Jan-13 13:34pm
Yes, thats Obvious. once should read the MSDN Remarks section before start using the method ;)
AyushJain1890 23-Jan-13 13:40pm
Thanks Jibesh For Your Help.
Jibesh 23-Jan-13 13:41pm
Glad to hear that. Cheers.
AyushJain1890 23-Jan-13 13:41pm
Also one More Question..

If you are reading any file and You have Completed reading up-to a Specific Line now You want to Know the offset i.e. The Position Up to Which you Have Completed Reading.

Any Sample Code Will Help.
Jibesh 23-Jan-13 13:44pm
You can use the Position property of the BaseStream to know current position in the stream.
AyushJain1890 23-Jan-13 14:00pm

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900