Question

Should I just load it in an array delete the selected row and save it back in? Or is there a more efficient way?

Example:

ddddd,aaaa,dddd,
ffff fffff,ffff,
ffff,ffff sssss,
ssss,dddd,ffff

I need to load all of this in a array, find the line that I wish to delete and delete it. Then save it over the old file.

Was it helpful?

Solution

There is no way to delete a portion of a text file and automatically shift all of the remaining data up to fill its place. The only way to do something like that is to rewrite the file.

The simplest solution, as you described, is to load the entire file into memory, make modifications to it in memory, and then overwrite the original file with the modified one from memory. The down-side to that approach is that you must load the entire file in memory all at the same time. That could be problematic if the file is particularly large.

If file-size is a concern, you will need to resort to some other method. For instance, you could open two file streams--one to read the original file (source) and one to write out the modified file (target). You could read one record at a time from the source stream and then only output it to the target stream if it is a record that you wish to keep. When you are done, you could then delete the original file and then rename the target file to take its place. It's more complicated, and a little slower, perhaps, but that way you never have more than one record loaded in memory at a time.

Edit

Based on your comments below, here is a simple example of how to load a file into an array of strings (one string per line in the file) and then output the lines to the console:

Dim lines() As String = File.ReadAllLines("test.csv")
For Each line As String In lines
    Console.WriteLine(line)
Next
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top