【问题标题】:Update on flat file database更新平面文件数据库
【发布时间】:2012-03-10 13:37:48
【问题描述】:

为了好玩,我尝试使用平面文件数据库来读取一些数据。使用的文件是文本文件和纯文本格式。我确实设计了它,以便有存储数据的格式,例如像下面这样的用户记录。

stackoverflow | 12345 | 12/12/2012 12:12:12 AM

其中上述数据的格式为username | password | lastlogin。我正在考虑使用用户名、密码验证用户的方法,如果发现更新上次登录日期并毫无例外地保存文件(其他用户也将使用相同的文件)

您能否用代码解释一下如何在登录成功时更新上次登录日期以及如何验证用户名密码。

我正在使用 C#、.NET 2.0。

现在psedocode如下;

File read DB.txt
      When text not empty
            split text in file with \n as separator character
            For each item in the output array split using pipe symbol
            check if [0] and [1] index match with username & password supplied
               if matched
                    How to update and save

【问题讨论】:

  • 请不要使用明文密码部署数据库,除非有最强烈的通知表明保存在其中的密码不安全。虽然用户不应该在两个不同的信任域之间使用同一个密码,但我们都知道他们会这样做,并且提供密码的纯文本副本可以极大地使攻击者更容易盗取密码。如果这是一个玩具,那很好,但要确保每个人都知道它是一个玩具。
  • @sarnold 谢谢。是的,这是一个玩具 :)

标签: c# .net database text-files flat-file


【解决方案1】:

如果性能没有问题,您应该通过根据更新操作添加/删除的字节数上下移动要更新的记录之后的每条记录来重建文件。比如:

public void UpdateRecordTest()
{
    string changedRecord =
        string.Format("{0}|{1}|{2}", UserName, Password, LoginDate);

    // get a copy of the new records in bytes. This varies based on the encoding
    byte[]changedRecordBytes;
    using(MemoryStream tempStream = new MemoryStream())
        using(StreamWriter tempWriter =
          new StreamWriter(tempStream, Encoding)) {
        tempWriter.WriteLine(changedRecord);
        changedRecordBytes = tempStream.ToArray();
    }

    using(MemoryStream tempStream = new MemoryStream) {
        // save the rest of the file in memory. When the file itself gets too big
        // you want to buffer this in a recursive manner (last part first)
        CurrentStream.CopyTo(tempStream);

        // adjust the position to move to the start of the current record
        CurrentStream.Position -= CurrentRecordBytes.Length;

        // write the temp data
        CurrentStream.WriteTo(changedRecordBytes);

        // copy the rest of the data
        tempStream.CopyTo(CurrentStream);
    }
}

如果性能有问题,您可能希望将当前记录设为 0,并在文件末尾重写它,从而创建间隙但确保无需移动任何数据。

【讨论】:

  • 我在这里看不到任何性能损失。 Streams 的工作速度是最快的。
  • 如果您的文件达到兆字节甚至千兆字节,那将是另一回事。移动 XXX 兆字节的数据(在磁盘上)可能需要一些时间
猜你喜欢
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 2015-04-04
  • 1970-01-01
  • 2011-09-16
  • 2010-11-29
  • 1970-01-01
相关资源
最近更新 更多