【问题标题】:Read Two Columns From CSV File in c#在 c# 中从 CSV 文件中读取两列
【发布时间】:2020-06-11 12:21:18
【问题描述】:

使用如下所示的 csv 文件:

usernames,passwords
us1,ps1
us2,ps2

我想要一个数组中的所有用户名和另一个数组中的所有密码。

当前代码: (尝试做一个与数据库交互的登录系统。)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;

namespace Login
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string[] usernames = new string[] { };

        string[] passwords = new string[] { };

        private void btnLogin_Click(object sender, EventArgs e)
        {
            lblLoginSucsess.Text = "";

            for (int i = 0; i < Math.Min(usernames.Length, passwords.Length); i++)
            {
                if ((usernames[i].ToLower() == txtUsnme.Text.ToLower()) && (passwords[i].ToLower() == txtPass.Text.ToLower()))
                {
                    lblLoginSucsess.Text = $"Welcome, {txtUsnme.Text}.";
                    // run calc
                    Process.Start("C:/Users/finch/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/HP Inc/Calculator.appref-ms");
                }
            }
        }
    }
}

如果你能帮忙,谢谢。

【问题讨论】:

  • 到目前为止您尝试了哪些方法,您在哪里遇到了困难?
  • 我知道如何在 python 中做到这一点,刚接触 c#,不知道从哪里开始。
  • 来自 Exar666Kun :请添加您到目前为止所做的代码,以便我们检查任何错误或以其他形式提供提示。要读取文本行,请检查 System.IO.File.ReadAllLines 以获取文件的所有行。剩下的就看你自己了。
  • 这能回答你的问题吗? Reading CSV file and storing values into an array

标签: c# arrays csv


【解决方案1】:

与其有两个单独的列表,不如有一个用户名/密码字典。您可以阅读 CSV 并通过

转换为字典
var dataLines = File.ReadAllLines(filePath);
var userPassDictionary = dataLines.Skip(1)
                                  .Select(x=> x.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries))
                                  .ToDictionary(x=> x.First().ToLower(),v=>v.Last());

现在您可以访问验证用户为

if (userPassDictionary[txtUsnme.Text.ToLower()] == txtPass.Text)
{

}

注意

还很奇怪地注意到您在比较密码时不区分大小写。虽然它可能取决于业务需求,但通常情况下,密码是区分大小写的。想突出显示它,以防万一,这是偶然的。

【讨论】:

    猜你喜欢
    • 2015-07-22
    • 2021-11-19
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多