C# 从正确的用户名行获取密码表单文件

C# 从正确的用户名行获取密码表单文件,c#,C#,我有一个username | password文件,其中username由一个管道与密码分开,每一行都有这样的username/password组合 虽然知道用户名,我想能够得到相应的密码 string text = System.IO.File.ReadAllText(@"C:\userPass.txt"); string username = "Johnny"; 如果改用ReadAllLines或ReadLines,您将从文件中获得一个可以搜索的行数组,将|字符上的每一行拆分。拆分的第一部

我有一个username | password文件,其中username由一个管道与密码分开,每一行都有这样的username/password组合

虽然知道用户名,我想能够得到相应的密码

string text = System.IO.File.ReadAllText(@"C:\userPass.txt");
string username = "Johnny";

如果改用
ReadAllLines
ReadLines
,您将从文件中获得一个可以搜索的行数组,将
|
字符上的每一行拆分。拆分的第一部分(索引
0
)是用户名,第二部分(索引“1”)是密码

在下面的代码中,我们使用
StartsWith
查找以用户名和“|”字符开头的第一行,然后返回该字符串的密码部分。如果找不到用户名,则返回
null

static string GetPassword(string userName, string filePath = @"C:\userPass.txt")
{
    if (userName == null) throw new ArgumentNullException(nameof(userName));

    if (!File.Exists(filePath))
        throw new FileNotFoundException("Cannot find specified file", filePath);

    return File.ReadLines(filePath)
        .Where(fileLine => fileLine.StartsWith(userName + "|"))
        .Select(fileLine => fileLine.Split('|')[1])
        .FirstOrDefault();
}
注意,这会对用户名进行区分大小写的比较。如果要允许不区分大小写,可以使用:

.Where(fileLine => fileLine.StartsWith(userName + "|", StringComparison.OrdinalIgnoreCase))
用法

string username = "Johnny";
string password = GetPassword(username); 

// If the password is null at this point, then either it 
// wasn't set or the username was not found in the file

感谢您提供了这个简洁明了的解决方案,但我在尝试运行此代码时遇到了“方法或操作未实现”的问题。您确实需要使用System.Linq的提示have
位于代码文件的顶部