1

我有一个程序可以将个人信息(姓名、姓氏、出生日期等)保存到名为 Records.dat 的 .dat 文件中。从文件中删除一个人的信息并将其替换为“已删除”或完全删除信息的理想方法是哪种?

4

1 回答 1

1

虽然我不确定你为什么不使用数据库(这真的没关系,所以这没什么大不了的)我会推荐一个逻辑删除(即不要真正删除它)。在平面文件的情况下,我建议在该行前面加上,DELETED|因为在读取要列出和/或搜索的行时很容易解析出来。所以,如果你在内存中有这条线,它可能看起来像这样:

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

然后您需要将其写line回文件。我不确定您是如何写入文件的,但假设您知道该记录在此示例的文件中的位置:

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);
    }
}
于 2013-04-19T12:33:30.420 回答