簡體   English   中英

使用 CsvHelper 從 CSV 文件中讀取

[英]Reading from CSV file with CsvHelper

我設法將列表中的內容寫入 CSV 文件。 現在我正在嘗試從創建的 CSV 文件中讀取並在控制台應用程序中顯示內容。 我遇到了一個例外,這導致我在互聯網上找到了一些可能的解決方案。 它們都不適用於我的控制台應用程序。 我希望你能幫助我。

我來自 Program.cs 的代碼調用 FileOperations.cs 中的方法:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using CsvHelper;

namespace GimpiesConsoleOOcsvListUI
{
    class Program
    {
        static void Main(string[] args)
        {
            // First line to skip a row and position all users correctly under the right headers
            User user0 = new User("", "", "", "");
            // Create user default instances
            User user1 = new User("Beheer", "beheer@gimpies.nl", "123", "admin");
            User user2 = new User("Inkoop", "inkoop@gimpies.nl", "123", "purchase");
            User user3 = new User("Verkoop", "verkoop@gimpies.nl", "123", "sales");

            // List of default users (with a list you can add, get and remove items in the list)
            List<User> users = new List<User>();
            users.Add(user0);
            users.Add(user1);
            users.Add(user2);
            users.Add(user3);

            // Create login instance
            LoginManager loginMgr = new LoginManager();

            // Create stock instance
            Stock stock = new Stock();

            // Create UserList instance
            UserList usrlst = new UserList();
            // Call method in UserList.cs
            usrlst.Users(users);

            Start:
            // Welcome message
            Console.WriteLine("Welcome to the Gimpies Console Application! Choose 1 to login or 2 to register as guest:");

            // Get input from user
            string input = Console.ReadLine();

            bool successfull = false;

            while (!successfull)
            {
                if(input == "1")
                {
                    Console.WriteLine("Enter your username:");
                    string username = Console.ReadLine();
                    Console.WriteLine("Enter your password:");
                    string password = Console.ReadLine();

                    foreach (User user in users)
                    {
                        if (username == user.UserName && password == user.PassWord && user.UserRole == "admin")
                            {
                                // Create Admin instance to be able to call methods in that class
                                Admin am = new Admin();
                                // Calling the method in Admin.cs to start Menu logic
                                am.AdminLoggedIn(); 
                                
                                successfull = true;
                                break; 
                            }

                        if (username == user.UserName && password == user.PassWord && user.UserRole == "purchase")
                            {
                                // Create Purchase instance to be able to call methods in that class
                                Purchase pc = new Purchase();
                                // Calling the method in Purchase.cs to start Menu logic
                                pc.PurchaseLoggedIn();
                                
                                successfull = true;
                                break; 
                            }
                        
                        if (username == user.UserName && password == user.PassWord && user.UserRole == "sales")
                            {
                                // Create Sales instance to be able to call methods in that class
                                Sales sl = new Sales();
                                // Calling the method in Sales.cs to start Menu logic
                                sl.SalesLoggedIn();
                                
                                successfull = true;
                                break; 
                            }
                        
                        if (username == user.UserName && password == user.PassWord && user.UserRole == "guest")
                            {
                                // Create Guest instance to be able to call methods in that class
                                Guest gt = new Guest();
                                // Calling the method in Guest.cs to start Menu logic
                                gt.GuestLoggedIn();
                                
                                successfull = true;
                                break; 
                            }
                    }

                        if (!successfull)
                            {
                                Console.WriteLine("Your username or password is incorrect, try again !!!");
                            }
                }

                else if (input == "2")
                {          
                    // Create instance to go to method in class RegisterManager.cs
                    RegisterManager rm = new RegisterManager();
                    rm.Register(users);   
                        
                    successfull = true;
                    goto Start;

                }

                else if (input == "3")
                {
                    FileOperations fo = new FileOperations();
                    // Calling the method from FileOperations.cs to write the List here to a CSV file
                    fo.WriteUsersToCSV(users);
                    goto Start;
                }

                else if (input == "4")
                {
                    FileOperations fo = new FileOperations();
                    // Calling the method from FileOperations.cs to write the List here to a CSV file
                    fo.ReadUsersFromCSV(users);
                    goto Start;
                }

                else
                {
                    Console.WriteLine("Try again !!!");
                    break;
                }
            }
            
            // // Loop over stored users within instances inside the list where users are added
            // foreach (User user in users)
            // {
            
            //     if(loginMgr.Login(user))
            //     {
            //         // Login successfull
            //         Console.WriteLine("Login user " + user.UserName);

            //     }
            //     else
            //     {
            //         // Not successfull

            //     }
            // }  
            
        }
    }
}

在 Program.cs 中,它是關於帶有輸入 ==“4”的 else if。

然后在 FileOperations.cs 中調用 ReadUsersFromCSV 方法:

using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
using System.Linq;
using CsvHelper;

namespace GimpiesConsoleOOcsvListUI
{
    // Handles CRUD within CSV files and able to save them
    public class FileOperations
    {
        // Writes to CSV file from List
        public void WriteUsersToCSV(List<User> users)
        {
            // using (var mem = new MemoryStream())
            // using (var writer = new StreamWriter(mem))
            using (var writer = new StreamWriter("users.csv"))
            using (var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                csvWriter.Configuration.Delimiter = ";";
                csvWriter.Configuration.HasHeaderRecord = true;
                csvWriter.Configuration.AutoMap<User>();
                csvWriter.WriteHeader<User>();
                csvWriter.WriteRecords(users);
                writer.Flush();
                // var result = Encoding.UTF8.GetString(mem.ToArray());
                // Console.WriteLine(result);
                Console.WriteLine("Data saved to users.csv");
            }
        }

        // Reads from CSV file and displays content from it (Work in progress...)
        public void ReadUsersFromCSV(List<User> users)
        {
            // using (var mem = new MemoryStream())
            // using (var writer = new StreamWriter(mem))
            using (var reader = new StreamReader("users.csv"))
            using (var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                // csvReader.Configuration.Delimiter = ";";
                // csvReader.Configuration.HasHeaderRecord = true;
                // csvReader.Configuration.AutoMap<User>();
                // csvReader.ReaderHeader<User>();
                // var records = csvReader.GetRecords<dynamic>();
                // reader.Flush();
                // var result = Encoding.UTF8.GetString(mem.ToArray());
                csvReader.Read();
                csvReader.ReadHeader();
                csvReader.Configuration.HeaderValidated = null;
                csvReader.Configuration.MissingFieldFound = null;
                var records = csvReader.GetRecords<User>();

                foreach (var record in records)
                {
                    Console.WriteLine(records);
                }
        
                // Console.WriteLine(records);
            }
        }

        // Writes to CSV file from List
        public void SaveGimpiesToCSV(List<Gimpies> gimpies)
        {
            // using (var mem = new MemoryStream())
            // using (var writer = new StreamWriter(mem))
            using (var writer = new StreamWriter("gimpies.csv"))
            using (var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                csvWriter.Configuration.Delimiter = ";";
                csvWriter.Configuration.HasHeaderRecord = true;
                csvWriter.Configuration.AutoMap<Gimpies>();
                csvWriter.WriteHeader<Gimpies>();
                csvWriter.WriteRecords(gimpies);
                writer.Flush();
                // var result = Encoding.UTF8.GetString(mem.ToArray());
                // Console.WriteLine(result);
            }
        }
            
        
    }
    
}

例外:

Unhandled exception. CsvHelper.MissingFieldException: Field with name 'username' does not exist. You can ignore missing fields by setting MissingFieldFound to null.
   at CsvHelper.Configuration.ConfigurationFunctions.MissingFieldFound(String[] headerNames, Int32 index, ReadingContext context)
   at CsvHelper.CsvReader.GetFieldIndex(String[] names, Int32 index, Boolean isTryGet, Boolean isOptional)
   at CsvHelper.CsvReader.GetFieldIndex(String name, Int32 index, Boolean isTryGet)
   at CsvHelper.Expressions.ExpressionManager.CreateConstructorArgumentExpressionsForMapping(ClassMap map, List`1 argumentExpressions)
   at CsvHelper.Expressions.ObjectRecordCreator.CreateCreateRecordDelegate(Type recordType)
   at CsvHelper.Expressions.RecordCreator.GetCreateRecordDelegate(Type recordType)
   at CsvHelper.Expressions.RecordCreator.Create[T]()
   at CsvHelper.Expressions.RecordManager.Create[T]()
   at CsvHelper.CsvReader.GetRecords[T]()+MoveNext()
   at GimpiesConsoleOOcsvListUI.FileOperations.ReadUsersFromCSV(List`1 users) in /home/pascalmariany/Projects/Csharp/GimpiesConsoleOOcsvList/GimpiesConsoleOOcsvListUI/FileOperations.cs:line 55
   at GimpiesConsoleOOcsvListUI.Program.Main(String[] args) in /home/pascalmariany/Projects/Csharp/GimpiesConsoleOOcsvList/GimpiesConsoleOOcsvListUI/Program.cs:line 132

CSV文件內容:

在此處輸入圖像描述

我的用戶.cs:

namespace GimpiesConsoleOOcsvListUI
{
    public class User
    {
        // Constructor
        public User(string username, string email, string password, string userrole)
        {
            _UserName = username;
            _Email = email;
            _Password = password;
            _UserRole = userrole;
        }

        private string _UserName;
        private string _Email;
        private string _Password;
        private string _UserRole;

        public string UserName
        {
            get { return _UserName; }
            set { _UserName = value; }
        }

        public string Email
        {
            get { return _Email; }
            set { _Email = value; }
        }

        public string PassWord
        {
            get { return _Password; }
            set { _Password = value; }
        }

        public string UserRole
        {
            get { return _UserRole; }
            set { _UserRole = value; }
        }
    }
}

我需要改變什么?

更新:

我閱讀了所有反饋,並在 FileOperations.cs 的方法中更改了一些內容:

// Reads from CSV file and displays content from it (Work in progress...)
        public void ReadUsersFromCSV(List<User> users)
        {
            // using (var mem = new MemoryStream())
            // using (var writer = new StreamWriter(mem))
            using (var reader = new StreamReader("users.csv"))
            using (var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                try
                {
                    csvReader.Configuration.Delimiter = ";";
                    csvReader.Configuration.IgnoreBlankLines = true;
                    csvReader.Configuration.HasHeaderRecord = true;
                    csvReader.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();
                    csvReader.Configuration.MissingFieldFound = null;
                    // csvReader.Configuration.AutoMap<User>();
                    // csvReader.ReaderHeader<User>();
                    // var records = csvReader.GetRecords<dynamic>();
                    // reader.Flush();
                    // var result = Encoding.UTF8.GetString(mem.ToArray());
                    csvReader.Read();
                    csvReader.ReadHeader();
                    // csvReader.Configuration.HeaderValidated = null;
                    
                    // Store all content inside a new List as objetcs
                    var records = csvReader.GetRecords<User>().ToList();
                    // users.ForEach(Console.WriteLine);
                    
                    foreach (var record in records)
                    {
                        Console.WriteLine(record);
                    }
                }
                catch (CsvHelper.HeaderValidationException exception)
                {
                    Console.WriteLine(exception);
                }
            }
        }

我現在沒有例外,但我得到的是 output:

GimpiesConsoleOOcsvListUI.User
GimpiesConsoleOOcsvListUI.User
GimpiesConsoleOOcsvListUI.User
GimpiesConsoleOOcsvListUI.User

這是正確的行數,但正如您所見,它不會顯示從 CSV 文件作為對象存儲到列表中的內容。

我錯過了什么嗎?

我設法解決了它。 我需要調整 foreach 循環:

public void ReadUsersFromCSV(List<User> users)
        {
            // using (var mem = new MemoryStream())
            // using (var writer = new StreamWriter(mem))
            using (var reader = new StreamReader("users.csv"))
            using (var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                try
                {
                    csvReader.Configuration.Delimiter = ";";
                    csvReader.Configuration.IgnoreBlankLines = true;
                    csvReader.Configuration.HasHeaderRecord = true;
                    csvReader.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();
                    csvReader.Configuration.MissingFieldFound = null;
                    csvReader.Read();
                    csvReader.ReadHeader();
                    
                    // Store all content inside a new List as objetcs
                    var records = csvReader.GetRecords<User>().ToList();
                    
                    // Loop through the List and show them in Console
                    foreach (var record in records)
                    {
                        Console.WriteLine($"{record.username } {record.email} {record.password} {record.userrole}");
                    }
                }
                catch (CsvHelper.HeaderValidationException exception)
                {
                    Console.WriteLine(exception);
                }
            }
        }

謝謝,但我從這個視頻中學到的最多:列表鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM