1 回答
TA贡献1725条经验 获得超7个赞
如果将Logins.txt文件更改为嵌入资源,则可以在运行时从程序集中加载该资源,如下所示:
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoginPage)).Assembly;
Stream stream = assembly.GetManifestResourceStream("YourAssembly.Logins.txt");
string text = "";
using (var reader = new System.IO.StreamReader (stream))
{
text = reader.ReadToEnd();
}
YouAssembly指的是构建项目时将生成的程序集 (dll) 的名称。如果你不知道这是什么,或者没有改变它,它可能与项目同名。
Xamarin 文档有一个很好的例子来说明这是如何完成的:Xamarin.Forms 中的文件处理
编辑:
在构造函数中执行此操作并处理内容以便您可以进行身份验证处理的更完整示例。
但首先,让我们定义一个 POCO 来保存用户名/密码的详细信息:
public class UserCredentials
{
public string Username {get;set;}
public string Password {get;set;}
}
添加一个属性来保存这个类:
List<UserCredentials> CredentialList {get;set;}
现在,在构造函数中:
public LoginPage()
{
InitializeComponent();
// Read in the content of the embedded resource, but let's read
// each line to make processing a little easier
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoginPage)).Assembly;
Stream stream = assembly.GetManifestResourceStream("YourAssembly.Logins.txt");
var textLines = new List<string>();
string line = null;
using (var reader = new System.IO.StreamReader (stream))
{
while ((line = sr.ReadLine()) != null)
{
textLines.Add(line);
}
}
// Init our cred list
this.CredentialList = new List<UserCredentials>();
// Read out the contents of the username/password combinations
foreach (var line in textLines)
{
// Grab items within new lines separated by a space and chuck them into their array
string[] components = line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
// Add the combination to our list
this.CredentialList.Add(new UserCredential
{
Username = user.Add(components[0]),
Password = pass.Add(components[0])
});
}
}
现在我们的登录变得容易多了。以前,我们首先检查用户名/密码是否都存在于我们的已知数据集中,然后检查它们在两个列表中是否位于相同的索引处。
public void btnLogin_Clicked(object sender, EventArgs e)
{
// Now can use linq to validate the user
// NOTE: this is case sensitive
if (this.CredentialList.Any(a => a.Username == txtUsername.Text && a.Password == txtPassword.Text))
{
// NOTE: you've only validated the user here, but aren't passing
// or storing any detail of who the currently logged in user is
Navigation.PushModalAsync(new HomeScreen());
}
else
{
DisplayAlert("Error", "The username or password you have entered is incorrect", "Ok");
}
}
- 1 回答
- 0 关注
- 318 浏览
添加回答
举报