-1

在使用 sytem.IO 方法使用某个文本文件之前,我需要获取它的位置。我试图让一个应用程序在所有计算机上运行,​​但是当我在计算机之间切换时,它似乎将我的 D:驱动器内存笔更改为和 F:驱动器,因此位置发生了变化。这是我一直在尝试使用的:

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");
    }
}

我知道这部分是错误的:

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

只是我不知道在那里使用什么。

任何帮助表示赞赏。

4

2 回答 2

1

您可能想查看允许您将文件名附加到路径以获取完全限定文件名的Path.Combine方法。

在您的示例中,假设文件存储在您的Application.StartupPath

baseLocation = Application.StartupPath;

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

注意:永远不要存储未加密的密码!

要读取用户名并将其与密码匹配,您可以执行以下操作:

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");
}    

并像这样报告结果:

if (userNameFound)
{
    if (passwordMatches)
        MessageBox.Show("Login successful!", "Success");
    else
        MessageBox.Show("Incorrect password", "Error");
}
else
{
    MessageBox.Show("Incorrect login", "Error");
}
于 2015-04-19T14:30:03.490 回答
1

使用此代码获取可移动驱动器名称并将您的文本文件名附加到它

DriveInfo[] ListDrives = DriveInfo.GetDrives();
string driveName=stirng.Empty;
foreach (DriveInfo Drive in ListDrives)
{
  if (Drive.DriveType == DriveType.Removable)
  {
    driveName=Drive.Name;
  }    
}
于 2015-04-19T14:42:56.583 回答