C#使用CSV文件 [英] C# Using an CSV file
问题描述
我对使用C#相当新,所以代码不需要很难
I am fairly new to using C# so code doesn't need to be difficult
我需要将CSV文件中的数据输入到程序中并且能够在将记录保存回CSV文件之前,将记录添加到其末尾。我正在努力寻找办法来完成所有这三项工作。通过在循环中输入
每行,向计数器添加1然后将其添加到数组中,我可以非常轻松地在Visual Basic中完成此操作,然后可以使用此计数器添加新数据。我还在循环中使用了一个函数;在C#帮助中似乎不存在的直到EOF(文件名)将被赞赏
I need to input the data from a CSV file into the program and be able to add a record to the end of it before saving it back to a CSV file. I am struggling to find a way to do all 3 of these. I am able to do it in Visual Basic really easily by inputting each line in a loop, adding 1 to a counter and then adding it to an array, this counter can then be used to add the new data. I also used a function in the loop; Do Until EOF(Filename) which doesn't seem to exist in C#Help would be appreciated
谢谢
Aiden
推荐答案
您好Aidenlvr,
Hi Aidenlvr,
感谢您在此发帖。
>>我需要将CSV文件中的数据输入到程序中
>>I need to input the data from a CSV file into the program
对于您的问题,您想如何从csv文件中读取数据?如果你想从csv文件读取数据到dataTable,你可以参考下面的代码。
For your question, how do you want to read the data from csv file? If you want to read the data from csv file to a dataTable, you could refer to the code below.
static void Main(string[] args)
{
string csv_file_path = @"test.csv";
DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
Console.ReadLine();
}
private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
}
return csvData;
}
>> 能够在之前添加记录到最后将其保存回CSV文件。
您要添加哪条记录?请提供更多详细信息。
What record you want to add? Please provide more details about this.
最好的问候,
Wendy
这篇关于C#使用CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!