C# 如何获取文本文件的位置
在使用sytem.IO方法使用某个文本文件之前,我需要获取该文件的位置。我试图让一个应用程序在所有计算机上运行,但当我在计算机之间切换时,它似乎会将我的D:drive内存笔更改为和F:drive,因此位置会发生变化。这就是我一直试图使用的:C# 如何获取文本文件的位置,c#,text-files,file-location,system.io.file,C#,Text Files,File Location,System.io.file,在使用sytem.IO方法使用某个文本文件之前,我需要获取该文件的位置。我试图让一个应用程序在所有计算机上运行,但当我在计算机之间切换时,它似乎会将我的D:drive内存笔更改为和F:drive,因此位置会发生变化。这就是我一直试图使用的: baseLocation = Application.ExecutablePath; string UsernameTXT = @PublicVariables.baseLocation + "//userName.txt" StreamReader us
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);
只是我不知道该用什么来代替
非常感谢您的帮助。您可能需要查看,它允许您将文件名附加到路径以获得完全限定的文件名 在您的示例中,假设文件存储在
应用程序中。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");
}
使用此代码获取可移动驱动器名并将文本文件名附加到其中
DriveInfo[] ListDrives = DriveInfo.GetDrives();
string driveName=stirng.Empty;
foreach (DriveInfo Drive in ListDrives)
{
if (Drive.DriveType == DriveType.Removable)
{
driveName=Drive.Name;
}
}
基本位置是一个比基本位置更长的路径,因此代码会使文本文件似乎位于可执行文件中OK,似乎您需要
StartupPath
。我只能重复这一点:永远不要在文本文件中存储未加密的密码!非常好用谢谢,我也知道以这种方式存储密码是不安全的,但这只是一个学校项目程序告诉我我缺少了“DriveInfo[]”的参考@Adam Higgins add System.IO name space first
DriveInfo[] ListDrives = DriveInfo.GetDrives();
string driveName=stirng.Empty;
foreach (DriveInfo Drive in ListDrives)
{
if (Drive.DriveType == DriveType.Removable)
{
driveName=Drive.Name;
}
}