2012-02-20 134 views
1

僅僅爲了一些樂趣,我試圖使用平面文件數據庫來讀取一些數據。使用的文件是文本文件和純文本格式。我確實設計了它,以便存儲數據的格式例如下面的用戶記錄。平面文件數據庫的更新

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 
+2

請不要使用明文密碼部署數據庫,除非最強的通知保存在其中的密碼不安全。儘管用戶決不應該在兩個不同的信任域之間使用一個密碼,但我們都知道他們這樣做,並且使密碼的純文本副本顯着可用,這使得攻擊者更容易竊取密碼。如果這是一個玩具,那很好,但要確保每個人都知道它是一個玩具。 – sarnold 2012-02-20 07:29:48

+0

@sarnold謝謝。是的,這是一個玩具:) – Deeptechtons 2012-02-20 08:25:31

回答

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淘汰當前記錄,並在文件末尾重寫它,從而產生差距,但要確保沒有數據移動。

+0

我沒有看到任何性能損失。流是他們工作中最快的。 – Deeptechtons 2012-02-20 07:26:22

+1

如果您的文件以兆字節甚至千兆字節計算,則會是一個不同的故事。移動XXX兆字節的數據(在磁盤上)可能需要時間 – Polity 2012-02-20 07:28:07