将数据写入 CSV 文件

本文关键字:CSV 文件 数据 | 更新日期: 2023-09-27 18:34:38

我有一个关于将数据写入CSV文件的问题。我有一个名为 test 的文件.csv其中有 2 个字段>帐号和关系 ID。现在我想在它旁边添加另一个字段:IBAN。IBAN 是第一行中的数据,由 SOAP 函数 BBANtoIBAN 验证

如何将 2 行数据帐号和关系 ID 保留在 CSV 中,并在第 3 行添加 IBAN?

这是我到目前为止的代码:

using (var client = new WebService.BANBICSoapClient("IBANBICSoap"))
{
    List<List<string>> dataList = new List<List<string>>();
    TextFieldParser parser = new TextFieldParser(@"C:'CSV'test.csv");
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(";");
    while (!parser.EndOfData)
    {
        List<string> data = new List<string>();
        string row = parser.ReadLine();
        try
        {
            string resultIBAN = client.BBANtoIBAN(row);
            if (resultIBAN != string.Empty)
               data.Add(resultIBAN);
            else
               data.Add("Accountnumber is not correct.");
        }
        catch (Exception msg)
        {
            Console.WriteLine(msg);
        }
        dataList.Add(data);
    }  
}

将数据写入 CSV 文件

我认为它是:

StreamReader sr = new StreamReader(@"C:'CSV'test.csv")
StreamWriter sw = new StreamWriter(@"C:'CSV'testOut.csv")
while (sr.Peek() >= 0) 
{
    string line = sr.ReadLine(); 

try
{
       string[] rowsArray = line.Split(';');
       string row = rowsArray[0];
       string resultIBAN = client.BBANtoIBAN(row);
       if (resultIBAN != string.Empty)
       {
           line +=";"+ resultIBAN;
       }
       else
       {
            line +=";"+"Accountnumber is not correct.";
       }
 }
 catch (Exception msg)
 {
     Console.WriteLine(msg);
 }
 sw.WriteLine(line) 
 }
sr.Close();
sw.Close();

我会做这样的事情来解析csv文件,并向数据列表添加一个额外的项目:

        List<List<string>> dataList = new List<List<string>>();
        string filename = @"C:'CSV'test.csv";
        using (StreamReader sr = new StreamReader(filename))
        {
            string fileContent = sr.ReadToEnd();
            foreach (string line in fileContent.Split(new string[] {Environment.NewLine},StringSplitOptions.RemoveEmptyEntries))
            {
                List<string> data = new List<string>();
                foreach (string field in line.Split(';'))
                {
                    data.Add(field);
                }
                try
                {
                    string resultIBAN = client.BBANtoIBAN(data[0]);
                    if (resultIBAN != string.Empty)
                    {
                        data.Add(resultIBAN);
                    }
                    else
                    {
                        data.Add("Accountnumber is not correct.");
                    }
                }
                catch (Exception msg)
                {
                    Console.WriteLine(msg);
                }
                dataList.Add(data);
            }