如何比较文本文件

时间:2016-02-25 05:09:28

标签: c# visual-studio

我正在为读取文本文件的ATM项目编写代码。文本文件采用以下格式编写:

帐号*姓名*图钉*支票余额*保存余额

所以,我将它传递给一个将它们分成数组的方法。

public void linesplitter (string line)
    {

     string[] split = line.Split('*');
        account = int.Parse(info [0]) ; 
        name = info [1] ; 
        pin = int.Parse(info [2]) ; 
        check = info [3] ; 
        saving = info [4] ; 
}

因此,当用户输入帐号时,会进入登录屏幕,输入与帐号关联的姓名和密码。

我的问题是如何将名称和图钉与帐号进行比较?

5 个答案:

答案 0 :(得分:1)

为您准备。

 List<AccountDetails> accountDetails = new List<AccountDetails>();

        //Declare class to store your info
        public class AccountDetails
        {
            public String account { get; set; }
            public String name { get; set; }
            public String pin { get; set; }
            public String check { get; set; }
            public String saving { get; set; }
        }

        //This function is a just an example, you need to expand it to fit your solution
        public void linesplitter(String line)
        {
            //You can place your text file reader code here. 
            //And call this function from Page_Load.
            AccountDetails dtl = new AccountDetails();
            string[] split = line.Split('*');
            dtl.account = int.Parse(info[0]);
            dtl.name = info[1];
            dtl.pin = int.Parse(info[2]);
            dtl.check = info[3];
            dtl.saving = info[4];

            //Every line from your text file will store to the Global List as declare in 1st line.
            accountDetails.Add(dtl);
        }


        //this is the function that trigger by your Button Event.
        //Pass in parameters to this function to get account details.
        //So the output for this function, something like 
        //if(result == null)
        //  login fail. etc
        public AccountDetails GetAccountDetails(String AccountNumber, String Name, String Pin)
        {
            var result = (from a in accountDetails
                          where a.account == AccountNumber
                          && a.name == Name
                          && a.pin == Pin
                          select a).FirstOrDefault();                                               

            return result;
        }

答案 1 :(得分:0)

我更喜欢为以下帐户创建一个类:

  public class Account
    {
        public int account { get; set; }
        public string name { get; set; }
        public int pin { get; set; }
        public string check { get; set; }
        public string saving { get; set; }
    }

然后形成一个accountObjects列表,其中包含存储帐户信息的文件中的所有帐户详细信息。迭代列表以检查是否有任何匹配的凭证可用。此完整方案的代码如下所示:

       List<Account> ATMAccountList = new List<Account>();
        foreach (var line in File.ReadAllLines("your Path Here"))
        {
            ATMAccountList.Add(linesplitter(line));
        }
         int accountNumberInput = 123, pinInput = 6565;
        // This will be the input values from the user
         bool matchFound = false;
        foreach (var accountItem in ATMAccountList)
        {
            if (accountItem.account == accountNumberInput && accountItem.pin == pinInput)
            {
                matchFound = true;
                break;
            }
        }
        if (matchFound)
        {
            //Proceed  with account
        }
        else
        {
            // display error ! in valid credential
        }          

方法linesplitter将被定义为像这样:

public Account linesplitter(string line)
    {
        Account AccountObject = new Account();
        string[] info = line.Split('*');
        AccountObject.account = int.Parse(info[0]);
        AccountObject.name = info[1];
        AccountObject.pin = int.Parse(info[2]);
        AccountObject.check = info[3];
        AccountObject.saving = info[4];
        return AccountObject;
    }

注意:

您可以使用 LINQ

执行相同的操作
        if (ATMAccountList.Where(x => x.account == accountNumberInput && x.pin == pinInput).Count() == 1)
        {
            //Proceed  with account
        }
        else
        {
            // display error ! in valid credentials
        }

答案 2 :(得分:0)

创建一个类来存储所有帐户信息。在阅读该行时,创建该类的实例并填写信息并存储在List中。现在比较名称和引脚,您只需使用Linq查询。

  Class AccountInfo
    {
     public int AccountNumber {get;set;}
     public string Name {get;set;}
     public int AtmPin {get;set;}
    public string Check {get;set;}
    public string Saving {get;set;}
    }

  //  Now in your Main program, use that class like this
    List<AccountInfo> accountInfoList= new List<AccountInfo>();
    foreach(string line in File.ReadAllLines("filename"))
    {
       AccountInfo ai =new AccountInfo();
      string[] split = line.Split('*');
            ai.AccountNumber = int.Parse(info [0]) ; 
            ai.Name = info [1] ; 
            ai.AtmPin = int.Parse(info [2]) ; 
            ai.Check = info [3] ; 
            ai.Saving = info [4] ; 
           accountInfoList.Add(ai);
    }

    // Some code to accept name and pin from user

    // Now compare name and pine like this

    var validationSuccessful = accountInfoList.Any(x=>x.AccountNumber==userEnteredAccountNumber &&
                        x.Name==userEnteredName &&
                        x.AtmPin==userEnteredPin);

    if(validationSuccessful)
    // Display next screen
    else
    // Display message log in failure

请记住这是最简单的方法。我假设您正在进行一些实践项目。实际ATM项目将具有很多安全性,并将使用Salt和Hash机制对Pin进行比较。它肯定会有一些数据库或服务。

正如Jannik所说,这是你在没有Linq查询的情况下进行比较的方法

bool validationSuccessful=false;

foreach(AccountInfo accountInfo in AccountInfoList)
{
  if(accountInfo.AccountNumber==userEnteredAccountNumber &&
                            accountInfo.Name==userEnteredName &&
                           accountInfo.AtmPin==userEnteredPin)
       {
        validationSuccessful = true;
         break;
       }
}

答案 3 :(得分:0)

作为一个选项,您必须将文本文件中的所有信息收集到包装类实例的集合中,然后在用户输入帐号后,您可以按编号在集合中找到一个项目,如果这样的项目存在,您希望所需的项目引脚和名称,进行验证检查等......

例如,您创建了类:

class AccountInfo
{
    public long AccountNumber { get;set; }
    public int Pin { get;set; }
    public string Name { get;set; }
    public string Check { get;set; }
    public string Saving { get;set; }
}

将您的文本数据转换为项目集合:

var textLines = sourceTextData.Split('\r\n').ToList();
var accountsCollection = textLines.Select(i => 
new AccountInfo
{ 
  AccountNumber = Convert.ToDouble(i.Split('*')[0]),
  Pin = Int32.Parse(i.Split('*')[1]),
  Name = i.Split('*')[2],
  Check = i.Split('*')[3],
  Saving = i.Split('*')[4]
}).ToList();

或者代替列表,您可以准备字典,其中字典键将是帐号。

答案 4 :(得分:0)

这是一个基本的控制台应用程序,可能会给你一些想法......

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleApplication1
{
class Program
{
    //private static XElement AccountData = new XElement("Root");
    private static DataSet dataSet = new DataSet();
    static void Main(string[] args)
    {
        DataSet dataSet = new DataSet();
        string[] readText = File.ReadAllLines(@"<Path to your account data file>\AccountData.txt");
        string strAccountNumber = string.Empty;
        string strPin = string.Empty;
        string strName = string.Empty;

        dataSet.ReadXml(new StringReader(new XElement("Root",
                            from str in readText
                            let fields = str.Split('*')
                            select new XElement("AccountData",
                                new XAttribute("AccountNo", fields[0]),
                                new XAttribute("Name", fields[1]),
                                new XAttribute("Pin", fields[2]),
                                new XAttribute("ChkBalance", fields[3]),
                                new XAttribute("SavBalance", fields[4])
                            )
                        ).ToString()));

        do
        {
            Console.WriteLine("Please enter your Account Number (press 'Q' to exit)");
            strAccountNumber = Console.ReadLine().ToLower();

            if (dataSet.Tables[0].Select(string.Format("AccountNo = '{0}'", strAccountNumber)).Count() == 1)
            {
                Console.WriteLine("Please enter your Pin");
                strPin = Console.ReadLine().ToLower();
                Console.WriteLine("Please enter your Name");
                strName = Console.ReadLine();

                if (dataSet.Tables[0].Select(string.Format("Pin = '{0}' AND Name = '{1}'", strPin, strName)).Count() == 1)
                {
                    DataRow[] result = dataSet.Tables[0].Select(string.Format("Pin = '{0}' AND Name = '{1}'", strPin, strName));
                    foreach (DataRow row in result)
                    {
                        Console.WriteLine(string.Format("Account Info for :: {0}", strName));
                        Console.WriteLine("{0}, {1}, {2}, {3}, {4}", row[0], row[1], row[2], row[3], row[4]);
                    }
                }
                else
                {
                    Console.WriteLine("Incorrect Details");
                }
            }
        } while (strAccountNumber != "q");
    }
}
}

不要忘记更换.....中的路径

string[] readText = File.ReadAllLines ....

带有数据路径.....