tags:

views:

1540

answers:

4

What is the best way to add text to the beginning of a file using C#?

I couldn't find a straightforward way to do this, but came up with a couple work-arounds.

  1. Open up new file, write the text that I wanted to add, append the text from the old file to the end of the new file.

  2. Since the text I want to add should be less than 200 characters, I was thinking that I could add white space characters to the beginning of the file, and then overwrite the white space with the text I wanted to add.

Has anyone else come across this problem, and if so, what did you do?

+1  A: 

I think the best way is to create a temp file. Add your text then read the contents of the original file adding it to the temp file. Then you can overwrite the original with the temp file.

Ryan Cook
Don't overwrite the original file, that will delete ACLs and ADSs. Use File.Replace.
Dour High Arch
+2  A: 

Adding to the beginning of a file (prepending as opposed to appending) is generally not a supported operation. Your #1 options is fine. If you can't write a temp file, you can pull the entire file into memory, preprend your data to the byte array and then overwrite it back out (this is only really feasible if your files are small and you don't have to have a bunch in memory at once because prepending the array is not necessarily easy without a copy either).

JP Alioto
Oh right, "prepend." Thanks! I couldn't think of the correct word.
Grace
A: 

You should be able to do this without opening a new file. Use the following File method:

public static FileStream Open(
    string path,
    FileMode mode,
    FileAccess access
)

Making sure to specify FileAccess.ReadWrite.

Using the FileStream returned from File.Open, read all of the existing data into memory. Then reset the pointer to the beginning of the file, write your new data, then write the existing data.

(If the file is big and/or you're suspicious of using too much memory, you can do this without having to read the whole file into memory, but implementing that is left as an exercise to the reader.)

JSBangs
+1  A: 

You can check out this post on Adding text to beginning and end of file in C#. Its for XML files, but easily modifiable for your use.

SwDevMan81