【问题标题】:How do I fix this username verification in c# with file handling?如何通过文件处理在 c# 中修复此用户名验证?
【发布时间】:2019-03-13 09:39:09
【问题描述】:

所以这部分代码是我程序的一小部分。它本质上是读取存储全名、银行余额、用户名和密码的用户信息文件。

我的问题是,为什么当我输入一个不在文件中的用户名时,如果有一个 if 语句说如果找不到用户名,那么它会抛出一个错误,然后转到注册方法?

    public static int player;
    public static void Username_Check()
    {
        string[] str = File.ReadAllText(@"X:\btec computing\unit 1\C sharp\online_casino_prog\user_info.csv").Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
        string[] users = new string[str.Length];
        Console.WriteLine("Enter your username. ");
        string username = Console.ReadLine();
        bool user_found = false;
        for (int i = 0; i < (str.Length); i++)
        {
            string[] person = str[i].Split(',');
            if (person[2] == username)
            {
                Console.WriteLine("Welcome back {0}!", person[0]);
                user_found = true;
                player = i;
                Password_Check();
            }
        }
        if (user_found == false)
        {
            Console.WriteLine("Sorry, we could not find an account linked to the username '{0}', Please register an account with us! ",username);
            Register();
        }
    }

这是我得到的错误:

未处理的异常:System.IndexOutOfRangeException:索引超出了数组的范围。 在 X:\btec 计算\单元 1\C sharp\online_casino_prog\online_casino_prog\Program.cs:line 58 中的 online_casino_prog.Program.Username_Check() 在 X:\btec 计算\单元 1\C sharp\online_casino_prog\online_casino_prog\Program.cs:line 30 中的 online_casino_prog.Program.Main(String[] args) 处

This snippet shows the csv file I am using to show the user information. It is formatted as such: first name, surname, username, password, balance

【问题讨论】:

  • 请包括您得到的错误。您的编译器/调试器已经完成了找出问题所在的工作,不要让我们通过不告诉我们您的编译器/调试器发现了什么而再次做同样的工作。
  • 您的文本文件末尾是否有空行?甚至最后一行换行? (或中间的任何空白行)如果是这样str[str.length-1] == "" 并对其进行拆分将使您在person[2] 上出现错误。添加检查if (person.length&gt;2)
  • 您的错误与您发布的代码不匹配。它可能不在您发布的代码中。请提供minimal reproducible example。现在可能是学习如何使用调试器的好时机。获取您选择的书籍或教程,并找出出现此错误的原因。
  • 这正是程序崩溃的地方,因为您没有在 Console.ReadLine() 中输入有效数字
  • 很公平:调试。更新后的错误证实了我之前所说的 - 您的输入没有 3 个逗号分隔的列,可能是因为它是空白的。您是否添加了我建议的任何一项检查?

标签: c# file-handling unhandled-exception


【解决方案1】:

您的代码可以使用 LINQ 进行简化

var username = Console.ReadLine();
var lines = File.ReadAllLines("./pathtoyour.csv").Select(line => line.Split(',')); // reads all lines from your csv then each line is transformed into an array of strings
var user = lines.FirstOrDefault(line => line[2] == username); // gets the first occurrence of the username, if no user is found returns null, otherwise user variable will be an array with the row data 

if (user != null)
  Console.WriteLine("Call PasswordCheck()");
else
  Console.WriteLine("Call Register()");

【讨论】:

  • 这很酷。这会摆脱我那里的所有代码吗?
  • 尝试在你的项目中实现它,你仍然需要设置player变量
猜你喜欢
  • 1970-01-01
  • 2012-07-27
  • 1970-01-01
  • 2022-07-25
  • 2022-11-16
  • 2014-06-25
  • 2011-12-31
  • 2017-02-21
  • 1970-01-01
相关资源
最近更新 更多