“未处理的异常:
System.IO.FileNotFoundException:找不到文件“ /Logins.txt”发生>
嗨,新手在xamarin c#中建立了一个非常基本的登录/注册系统,该系统使用Systsem.IO中的StreamReader读取带有存储的用户名和密码的文本文件。 txt文件与.cs文件本身位于同一目录中,并且在解决方案资源管理器中可见。 我已经尝试过没有成功的完整路径,并且以管理员身份运行,以防万一这与权限有关。 有什么问题吗?
ng build --base-href /ui --deploy-url /ui
答案 0 :(得分:0)
如果将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文档提供了一个很好的示例,说明了如何完成此操作:File Handling in 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");
}
}