当前位置: 首页 > 知识库问答 >
问题:

找不到txt文件StreamReader

吕征
2023-03-14

'未处理的异常:

系统。IO. FileNotFoundException:找不到文件"/Logins.txt"发生'

大家好,新手在xamarin c#中使用Systsem中的StreamReader创建了一个非常基本的登录/注册系统。IO读取包含存储用户名和密码的文本文件。txt文件与位于同一目录中。cs文件本身,并在解决方案资源管理器中可见。我尝试了完整的路径,但没有成功,我以管理员的身份运行,以防它与权限有关。有什么问题吗?

public partial class LoginPage : ContentPage
{
    public LoginPage()
    {
        InitializeComponent();
    }
    List<string> user = new List<string>();
    List<string> pass = new List<string>();

    public void btnLogin_Clicked(object sender, EventArgs e)
    {
        //Read the txt
        StreamReader sr = new StreamReader("Logins.txt");
        string line = "";

        //Read every line until there is nothing in the next line
        while ((line = sr.ReadLine()) != null)
        {
            //Grab items within new lines separated by a space and chuck them into their array
            string[] components = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            user.Add(components[0]);
            pass.Add(components[0]);
        }
        //Check entries are on the same line and match
        if (user.Contains(txtUsername.Text) && pass.Contains(txtPassword.Text) && Array.IndexOf(user.ToArray(), txtUsername.Text) == Array.IndexOf(pass.ToArray(), txtPassword.Text))
        {
            Navigation.PushModalAsync(new HomeScreen());
        }
        else
            DisplayAlert("Error", "The username or password you have entered is incorrect", "Ok");
    }
    private void Cancel_Clicked(object sender, EventArgs e)
    {
        Navigation.PushModalAsync(new MainPage());
    }
}

共有1个答案

欧阳君浩
2023-03-14

如果您将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中的文件处理。表单

编辑:

这是一个在构造函数中执行此操作并处理内容的更完整示例,以便您可以执行身份验证处理。

但首先,让我们定义一个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");
    }
}
 类似资料:
  • 埃弗里翁。我正在尝试创建一个基本表单,将姓氏和姓氏保存在一个文本文件中,因此当我必须登录时,我将从txt文件中检索它们,但显然我对txt文件的目录做了一些错误 现在我更新了代码,出现了这个安全错误 警告:fopen(/home/sbau01/public_www/php/fma/data/data.txt):无法打开流:在/home/sbau01/public_www/php/fma/form中的

  • 问题内容: 我最近一直在开发一个程序,该程序可以从Java程序编译并运行C ++程序,我已经使一切基本正常(或至少据我所知),但是后来我注意到有些东西被打印到错误流中: 如您所见,如果我通过SSH而不是Java代码进行操作,它会起作用吗? Java代码: 感谢您的任何帮助,它已得到批准! 问题答案: 告诉你问题所在。 您的一级引号过多,因此您正在寻找而不是。 该的Runtime.exec文档说:

  • 在spring Java框架中,我使用context.xml文件创建bean,然后用加载它。 我的程序抛出异常。 文件存在。我使用Gradle进行依赖关系管理,并且我的src文件夹(文件所在的位置)在intellij中标记为resource。我知道由于某种原因,即使我的src文件夹应该包含在classpath变量中,但gradle run任务只是不能从这里抓取它。 当我使用时,所有的工作都很好,但

  • PhpStorm 2021.1.1 Mac M1 11.3 当我尝试使用或查找文件时,PhpStorm未能找到该文件。似乎正在尝试从目录,而不是在项目目录中搜索。 我试图< code >文件|无效缓存,运气不好。有人能帮忙吗?

  • 问题内容: 这是我的代码: 我想在test.txt文件中找到一些单词 “ the” 。问题是当我找到第一个 “ the”时 ,我的程序停止寻找更多东西。 当诸如 “ then” 之类的单词被我的程序理解为 “ the” 一词时。 问题答案: 不区分大小写地使用Regexes,并使用单词边界查找“ the”的所有实例和变体。 无法区分 “ the” 和 “ then”, 因为它们均以“ the”开头