Hossam Tebry
Hossam Tebry

Reputation: 13

IO.StreamWriter overwrite

I'm trying to add some characters into the first line of an existing text file , streamwriter.write is overwrite the line with length of the characters I added is there a very simple way to write the text I want or characters I want to add without overwrite the existing ones and with no use of streamreader or temp file. My Code:

        FileStream fs = new FileStream(@"G:\PayLoad.txt",FileMode.Open);
        StreamWriter sw = new StreamWriter(fs); \\ IF First line is ==>> 123456789
        sw.BaseStream.Position = 0;
        sw.Write("REM ");      \\ This will overwrite to be ==>> REM 56789 
        sw.Close();     \\ we want it to be ==>> REM 123456789

Upvotes: 1

Views: 225

Answers (1)

DarkSquirrel42
DarkSquirrel42

Reputation: 10257

on the most operating systems, files don't work that way ... in general, there is no such thing as "insert" ... you could try Keith's approach and use a memory mapped file ... you would have to read the file from the position where you want to insert to its end, then overwrite the desired part where your insert should happen and then write the part you have read after the part you have inserted ... take into account that the file could be really large, and that it could be difficult to read all of it at once into memory ...

so to avoid an out-of-memory situation you could take a certain block size, let's say up to a few megabytes and handle those blocks instead ...

in the beginning you have a buffer that holds the data you want to insert (insBuffer)

then you will need a buffer to hold a block of the that needs to be moved towards the end of the file (tmpBuffer)

the procedure would be like this:

go to the position in the file where you want to insert (lets call this position insOffset)

from that position, read the desired block size of data into tmpBuffer (or if the remaining part of the file is less, then just that)

now overwrite the file at the position where you want to insert and move insOffset behind the data you just inserted

now the current contents of tmpBuffer need to be inserted at the position marked by insOffset ... as you can see the procedure repeats here until you reach the end of the file ...

Upvotes: 1

Related Questions