如何使用CsvHelper软件包将C#List写入CSV
我有一个简单的控制台应用程序,它在Program.cs中包含3个用户的列表。在Program.cs中,我想调用如何使用CsvHelper软件包将C#List写入CSV,c#,.net,list,csv,csvhelper,C#,.net,List,Csv,Csvhelper,我有一个简单的控制台应用程序,它在Program.cs中包含3个用户的列表。在Program.cs中,我想调用FileOperations.cs中的一个方法 首先,我的程序.cs: using System; using System.Collections.Generic; using System.IO; using System.Text; using CsvHelper; namespace GimpiesConsoleOOcsvListUI { class Program
FileOperations.cs
中的一个方法
首先,我的程序.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
// }
// }
}
}
}
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行遇到以下错误:
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
// }
// }
}
}
}
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);
}
}
}
}
流作者
参数1:无法从System.IO.StreamWriter
转换为CsvHelper.ISerializer
第23行:
用户用户
参数1:无法从GimpiesConsolleoCsvListui.User
转换为System.Collections.IEnumerable
我是C的新手,所以我希望你不要介意这是一个简单的问题 由于在这两种情况下都传递了错误的参数类型,因此会出现错误。
CsvWriter
没有只接受一个参数为TextWriter
的构造函数。我对这个图书馆不是很熟悉,但我相信它可能在过去就已经做过了。我怀疑您从internet上以前的示例中复制了代码,这些示例已经过时
解决此问题的简单方法是再添加两个参数,因此:
using (var csvWriter = new CsvWriter(writer, CultureInfo.CurrentCulture, false))
第二个错误是因为CsvWriter.WriteRecords
需要一个IEnumerable
参数,而不是一个实例。要解决此问题,您需要将您的列表
传递给它,这样整个代码就变成:
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);
}
}
public void SaveToCSV(列出用户)
{
使用(var mem=new MemoryStream())
使用(var编写器=新StreamWriter(mem))
使用(var csvWriter=new csvWriter(writer,CultureInfo.CurrentCulture,false))
{
csvWriter.Configuration.Delimiter=“;”;
csvWriter.Configuration.HasHeaderRecord=true;
csvWriter.Configuration.AutoMap();
csvWriter.WriteHeader();
csvWriter.WriterRecords(用户);
writer.Flush();
var result=Encoding.UTF8.GetString(mem.ToArray());
控制台写入线(结果);
}
}
如果要序列化单个用户对象并显示其序列化的标题和值,可以尝试以下代码:
public void SaveToCSV(User user)
{
using (var writer = new StringWriter())
using (var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture, leaveOpen: true))
{
csvWriter.Configuration.Delimiter = ";";
csvWriter.Configuration.HasHeaderRecord = true;
csvWriter.Configuration.AutoMap<User>();
csvWriter.WriteHeader<User>();
csvWriter.WriteRecord(user);
csvWriter.Flush();
var result = writer.ToString();
Console.WriteLine(result);
}
}
在第二个示例中,您不需要调用
Flush
,因为using
block的末尾为您调用了它,并且您对其范围内的CSV内容不感兴趣。我不了解您的代码流;您有一个要保存的用户列表,您有一个类,该类的方法只将单个用户保存到内存流中(因此不保存到磁盘),然后立即丢弃内存流,这样就不会在任何地方保存任何内容。可能值得仔细阅读您的代码并对算法进行注释,这样您就有了实现目标所需的母语步骤集,然后您就可以评估注释下的c#是否真的符合注释所述;“先用英语(/你的母语)写,然后翻译成c#”不要使用goto
谢谢你的例子和解释。乔纳森:多亏了你的榜样,我才迈出了几步。还有msmolcic谢谢!你的反馈和例子都让它很有效。现在只剩下一些微调了!:-谢谢你的努力。我也要试一试。我的下一步确实是写入CSV文件。当我尝试了你的所有技巧后,我会回来的。我尝试了写csv文件,它成功了!我现在唯一的问题是列表的第一个条目写在标题项旁边。所以它变成了这样:名字;电子邮件;密码;管理admin@admin.com ; 123销售;sales@admin.com ; 123购买;purchase@admin.com ; 123也许你知道如何解决这个问题?我用一个空的第一个用户做了一个临时解决方案://创建用户默认实例user user0=new user(“,”,”);用户user1=新用户(“Beheer”beheer@gimpies.nl", "123"); 用户user2=新用户(“Inkoop”inkoop@gimpies.nl", "123"); 用户user3=新用户(“Verkoop”verkoop@gimpies.nl", "123");代码>