Georgebuk
Georgebuk

Reputation: 11

Delete or change text from .dat file

I have a program which saves a persons information (Name, Surname, DOB etc.) to a .dat file named Records.dat. Which is the ideal method of deleting one person's information from the file and either replacing it with "DELETED" or just delete the information entirely?

Upvotes: 1

Views: 994

Answers (1)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Though I'm unsure why you're not leveraging a database (and it really doesn't matter so it's not a big deal) I'm going to recommend a logical delete (i.e. don't really delete it). In the case of a flat file I would recommend prefacing the line with DELETED| because that's really easy to parse out when reading rows to list and or searching. So, if you had the line in memory it might look something like this:

var line // you've already assigned this
line = string.Format("DELETED|{0}", line);

and then you'll need to write that line back to the file. I'm not sure how you're writing to the file, but let's assume you know the position of that record in the file for this example:

int startIndex // you have already assigned this somewhere
               // it's the starting index of this line

using (FileStream fs = new FileStream("path to file", FileMode.Create, FileAccess.Write))
{
    using (BinaryWriter bw = new BinaryWriter(fs))
    {
        bw.Position = startIndex
        bw.Write(Encoding.Default.GetBytes(line), 0, line.Length);
    }
}

Upvotes: 1

Related Questions