-1

I need to get the location of a certain textfile before i user it with sytem.IO methods. I am trying to get an application working on all computer but when i switch between computers it seems to change my D: drive memory pen to and F: drive so the location changes. This is what I have been trying to use:

baseLocation = Application.ExecutablePath;

string UsernameTXT = @PublicVariables.baseLocation + "//userName.txt"
StreamReader user_Login = new StreamReader(UsernameTXT);
string PasswordTXT = @PublicVariables.baseLocation + "//userPass.txt"
StreamReader pass_Login = new StreamReader(PasswordTXT);

while (pass_Login.Peek() != -1)
{
    user = user_Login.ReadLine();
    pass = pass_Login.ReadLine();

    if ((user == textBox1.Text) && (pass == textBox2.Text))
    {
        MessageBox.Show("Login successful!",
            "Success");
    }
}

I know this part is wrong:

string UsernameTXT = @PublicVariables.baseLocation + "//userName.txt"
StreamReader user_Login = new StreamReader(UsernameTXT);
string PasswordTXT = @PublicVariables.baseLocation + "//userPass.txt"
StreamReader pass_Login = new StreamReader(PasswordTXT);

its just that i have no idea what to use there instead.

Any help is appreciated.

Adam Higgins
  • 705
  • 1
  • 10
  • 25

2 Answers2

1

You may want to have a look at the Path.Combine method that allows you to attach a file name to a path to get the fully qualified file name.

In your example, assuming the files are stored in your Application.StartupPath:

baseLocation = Application.StartupPath;

string usernameFile = Path.Combine(baseLocation, "userName.txt");
string passwordFile = Path.Combine(baseLocation, "userPass.txt");

NOTE: Don't ever store unencrypted passwords!

To read and match a user name with a password, you can then do the following:

var userNameFound = false;
ar passwordMatches = false;
try
{
    var ndx = 0
    var passwords = File.ReadAllLines(passwordFile);
    foreach (var userName in File.ReadAllLines(usernameFile))
    {
        userNameFound = userName.Equals(textBox1.Text);
        if (userNameFound && ndx < passwords.Length)
        {
            passwordMatches = passwords[ndx].Equals(textBox2.Text);
            break; // no need to search further.
        }
        ndx++;
    }
}
catch (FileNotFoundException) 
{ 
    MessageBox.Show("Failed to open files", "Error");
}    

And report the result like this:

if (userNameFound)
{
    if (passwordMatches)
        MessageBox.Show("Login successful!", "Success");
    else
        MessageBox.Show("Incorrect password", "Error");
}
else
{
    MessageBox.Show("Incorrect login", "Error");
}
Alex
  • 13,024
  • 33
  • 62
1

Use this code to get the removable drive name and append your text file name to it

DriveInfo[] ListDrives = DriveInfo.GetDrives();
string driveName=stirng.Empty;
foreach (DriveInfo Drive in ListDrives)
{
  if (Drive.DriveType == DriveType.Removable)
  {
    driveName=Drive.Name;
  }    
}
VIVEK P S
  • 315
  • 2
  • 15