如何获取文本文件的位置

时间:2015-04-19 14:26:08

标签: c# text-files file-location system.io.file

在使用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);

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

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您可能需要查看允许您将文件名附加到路径以获取完全限定文件名的Path.Combine method

在您的示例中,假设文件存储在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");
}

答案 1 :(得分:1)

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

DriveInfo[] ListDrives = DriveInfo.GetDrives();
string driveName=stirng.Empty;
foreach (DriveInfo Drive in ListDrives)
{
  if (Drive.DriveType == DriveType.Removable)
  {
    driveName=Drive.Name;
  }    
}