FileStream - File editing

G

Guest

I have a file opened as a FileStream.
I have a StreamReader and StreamWriter object opened, referencing the
FileStream object.

My aim is to read lines from the file until I find the line where there is a
unique comment as a place holder.
I would then like to use the StreamWriter to insert lines after this comment
and save the file.

How do I instruct the StreamWriter to find the line position based on the
current position that the StreamReader is in?

Code so far:

FileStream fs = new FileStream("FILENAME",FileMode.Open,
FileAccess.ReadWrite);
using(StreamReader sr = new StreamReader(fs))
{
sr.BaseStream.Seek(0,SeekOrigin.Begin);
string line = sr.ReadLine();
while(!line.StartsWith("// start"))
{
line = sr.ReadLine();
}
// at this point the reader should be at the correct position within the file
using(StreamWriter sw = new StreamWriter(fs))
{
sw.BaseStream.Seek(sr.BaseStream.Position, SeekOrigin.Current);
sw.WriteLine("test");
sw.Flush();
}
}
fs.Close();
 
N

Nicholas Paldino [.NET/C# MVP]

sbparsons,

You really can't insert content into the middle of a file. What you
will have to do is actually create a new file, and copy over the content to
the new file as you need to.

Then, when you are done writing to the new file, you would delete the
old file, and move the new file to the old file's location.

Also, you should wrap your FileStream in a using statement as well.

Hope this helps.
 
W

William Stacey [MVP]

I may be easier to load the file into a MemoryStream and work on the file
with that stream. Then write the file back out when the user commits the
changes.
 
G

Guest

Hi William,

Thanks for the reply. Would it be possible to supply a very quick sample, as
I haven't used the MemoryStream object yet?
Something along the lines of a file containing
1
2
4
5
Open the file into a MemoryStream and search for the number 2, then insert a
3 between the 2 and 4 and close and save the file?

Thanks in advance,
Sean
 

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

Similar Threads


Top