For just some fun i am trying to use Flat File databases to read some data.The file used is text file and plain text format. I did design it such that there is format of storing the data for example a user record like below.
stackoverflow | 12345 | 12/12/2012 12:12:12 AM
where the above data if of format username | password | lastlogin
. I am thinking of what are the ways i can validate a user using username, password and if found update the last login date and save the file without a exception(other users will also be using same file)
Could you explain with a code how to update last logindate when login successfull & how to validate username password.
I am using C#, .NET 2.0..
Right now psedocode is like below;
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
If performance is no problem, you should rebuild the file by moving every record coming after the record you want to update up or down depending on the number of bytes added/removed due to the update operation. Something like:
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);
}
}
If performance is a problem, you might want to 0 out the current record and rewrite it at the end of the file thereby creating gaps but ensuring that no data has to be moved.