.net 如何使用CsvHelper包将C#列表写入CSV

ztmd8pv5  于 2023-02-20  发布在  .NET
关注(0)|答案(3)|浏览(290)

我有一个简单的控制台应用程序,在Program.cs中包含3个用户的列表。在Program.cs中,我想调用FileOperations.cs中的方法。
首先我的Program.cs

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

namespace GimpiesConsoleOOcsvListUI
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create user default instances
            User user0 = new User("Beheer", "beheer@gimpies.nl", "123");
            User user1 = new User("Inkoop", "inkoop@gimpies.nl", "123");
            User user2 = new User("Verkoop", "verkoop@gimpies.nl", "123");

            // List of 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);

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

            Start:
            // Welcome message
            Console.WriteLine("Welcome to GimpiesTerminal! Choose 1 to login or 2 to register:");

            // 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)
                            {
                                Console.WriteLine("You have successfully logged in !!!");
                                Console.ReadLine();
                                successfull = true;
                            break;  
                            }
                    }
                        if (!successfull)
                            {
                                Console.WriteLine("Your username or password is incorrect, try again !!!");
                            }
                }
                else if (input == "2")
                {
                        // Get user input
                        Console.WriteLine("Enter your username:");
                        string username = Console.ReadLine();

                        Console.WriteLine("Enter your email:");
                        string email = Console.ReadLine();

                        Console.WriteLine("Enter your password:");
                        string password = Console.ReadLine();

                        // Create fresh instance to save input in memory
                        User user = new User(username, email, password);

                        // Adds the user to the excisting list
                        users.Add(user);
                        
                        successfull = true;
                        goto Start;
                }
                else if (input == "3")
                {
                    // Here I want to call the method from FileOperations.cs to write the List here to a CSV file.
                }
                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

            //     }
            // }  
            
        }
    }
}

下面是我的FileOperations.cs

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

namespace GimpiesConsoleOOcsvListUI
{
    public class FileOperations
    {
        // Handles CRUD within CSV files and able to save them
        public void SaveToCSV(User user)
        {
            using (var mem = new MemoryStream())
            using (var writer = new StreamWriter(mem))
            using (var csvWriter = new CsvWriter(writer))
            {
                csvWriter.Configuration.Delimiter = ";";
                csvWriter.Configuration.HasHeaderRecord = true;
                csvWriter.Configuration.AutoMap<User>();

                csvWriter.WriteHeader<User>();
                csvWriter.WriteRecords(user);

                writer.Flush();
                var result = Encoding.UTF8.GetString(mem.ToArray());
                Console.WriteLine(result);
            }
        }
    } 
}

我在FileOperations.cs的第16行得到以下错误:
StreamWriter编写器参数1:无法从System.IO.StreamWriter转换为CsvHelper.ISerializer
第23行:
用户user参数1:无法从GimpiesConsoleOOcsvListUI.User转换为System.Collections.IEnumerable
我是C#的新手,所以我希望你不要介意这是一个简单的解决问题!:-)

pinkon5k

pinkon5k1#

如果要序列化单个用户对象并显示其序列化的标头和值,可以尝试以下代码段:

public void SaveToCSV(List<User> users)
{
    var csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
    {
        HasHeaderRecord = true,
        Delimiter = ",",
        Encoding = Encoding.UTF8
    };

    using (var mem = new MemoryStream())
    using (var writer = new StreamWriter(mem))
    using (var csvWriter = new CsvWriter(writer, csvConfig))
    {
        csvWriter.WriteHeader<User>();
        csvWriter.WriteRecords(users);

        writer.Flush();
        var result = Encoding.UTF8.GetString(mem.ToArray());
        Console.WriteLine(result);
    }
}

它使用库的CsvWriter所需的简单StringWriter示例,并使用InvariantCulture info进行内容序列化。在本例中,第三个参数leaveOpen必须设置为true,因为您对using块范围内StringWriter的内容感兴趣。您当前正在传递User的单个示例,因此必须调用WriteRecord方法,而不是WriteRecords
如果你想把它写入实际的文件,你必须做一点不同:

public void SaveToCSV(List<User> users)
{
    var csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
    {
        HasHeaderRecord = true,
        Delimiter = ",",
        Encoding = Encoding.UTF8
    };

    using (var writer = new StreamWriter(@"path\to\your\file.csv"))
    using (var csvWriter = new CsvWriter(writer, csvConfig))
    {
        csvWriter.WriteHeader<User>();
        csvWriter.WriteRecords(users);
    }
}

在第二个示例中,您不需要调用Flush,因为using块的末尾会为您调用它,并且您对它的作用域中的CSV内容不感兴趣。

chhqkbe1

chhqkbe12#

您得到错误是因为您在这两种情况下传递了错误的参数类型。CsvWriter没有一个构造函数,它只接受一个TextWriter参数。我不是很熟悉这个库,但我相信它可能在过去做过。我怀疑您从互联网上以前的示例复制了您的代码,这些代码已经过时了。
解决这个问题的简单方法是再添加两个参数,如下所示:

using (var csvWriter = new CsvWriter(writer, CultureInfo.CurrentCulture, false))

第二个错误是因为CsvWriter.WriteRecords需要一个IEnumerable参数,而不是一个示例。要解决这个问题,你需要传递你的List<User>,所以整个代码变成:

public void SaveToCSV(List<User> users)
{
    using (var mem = new MemoryStream())
    using (var writer = new StreamWriter(mem))
    using (var csvWriter = new CsvWriter(writer, CultureInfo.CurrentCulture, false))
    {
        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);
    }
}
jv4diomz

jv4diomz3#

由于csvhelper中的this发生了变化,因此给出的示例将不起作用。
@Jonathn的更新代码如下所示-

public void SaveToCSV(List<User> users)
    {
        var csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
        {
            HasHeaderRecord = true,
            Delimiter = ",",
            Encoding = Encoding.UTF8
        };

        using (var mem = new MemoryStream())
        using (var writer = new StreamWriter(mem))
        using (var csvWriter = new CsvWriter(writer, csvConfig))
        {
            csvWriter.WriteHeader<User>();
            csvWriter.WriteRecords(users);

            writer.Flush();
            var result = Encoding.UTF8.GetString(mem.ToArray());
            Console.WriteLine(result);
        }
    }

相关问题