Click here to Skip to main content
12,554,623 members (58,654 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# C#4.0
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 ..?
Posted 17-Jan-13 8:03am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.161021.1 | Last Updated 17 Jan 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100