[Solved] Random access file [closed]


I’ll give an example and hope it will help you get what you want.

In this example your Registered.txt file should look like:
Smartsasse,myPassword
OlofBoll,P@ssword

//var path = @"C:\Registered.txt";
var path = "Registered.txt";

var allLines = System.IO.File.ReadAllLines(path);

var userInfo = allLines.Select(l => l.Split(',')).Select(s => new
{
    Username = s[0],
    Password = s[1]
}).ToList();

var user = userInfo.FirstOrDefault(ui => ui.Username.ToLowerInvariant() == this.UserNameTextBox.Text.Trim().ToLowerInvarant());

if (user != null && user.Password == this.PasswordTextBox)
{
    // Login is okay
    this.ViewState["loggedInUser"] = user.Username;
}
else
{
    // Show error message
    throw new Exception("Couldn't login, invalid username or password.");
}

You will need to reference “System.Linq” by “using System.Linq;”. If not you could change some of the code to:

bool success = false;
foreach (var line in allLines)
{
    var username = line.Split(',')[0];
    var password = line.Split(',')[1];

    if (username == this.UserNameTextBox.Text && password == this.PasswordTextBox.Text)
    {
        // Login
        // this.ViewState["loggedInUser"] = user.Username;
        success = true;
        break;
    }
}

if (success == false)
{
    // Show error
    throw new Exception("Couldn't login, invalid username or password.");
}

This code will not run just by it self but might help you get what you want.

solved Random access file [closed]