Add and remove data from file
Is t possible to:
- Add data to a certain offset in a file without overwriting original data from that offset, thus expanding the file?
- Remove data from a certain offset and length in a file, instead of making a new file of the two desired parts of data from the original file?
Thanks!
[330 byte] By [
APMadsen] at [2007-12-22]
This can be difficult to do robustly. What I recommend is that you read the original file into memory, make your changes, and then write it back out. You don't want to be in a situation where, say, you have adjusted the file by creating space at your offset, but your program crashes or the computer turns off or something else happens and your app doesn't get a chance to write the data there. You now have corrupted files.
I'd almost recommend writing the new file to a temporary file location, and then swapping it with your original file. Of course, it depends on how robust you want your application to be.
And reading files into memory is whether it be a text file or a binary file is easy using
My.Computer.Filesystem. (readalltext or readallbytes)
The manipulating the in memory data - by removing , adding or changing items etc. before writing this stuff back to a file using the companion function
My.Computer.Filesystem. (writealltext or writeallbytes)
As tim suggested there are many ways you can make this more robust to ensure that you dont get corrupted files but this way is simple and for small to medium files the file reading and writing may prove to be fast enough. So you get a easy to maintain - simple to debug solution.
Sure performance may be an issue with files this size and the stringbuilder class may be the best option.
Also remember windows uses virtual memory, so it will page items in an out of memory if you dont physically have 100Mb free in your machine at the time.
Are we talking like a batch process to update this file or are you talking about an interactive application - Is it possible that you could use a database to do interactive parts of the process and then create an export option to output the required format file.