使用 csvhelper 操作 csv 结构和内容

Manipulating csv structure and content with csvhelper

我一直在尝试通读一些存储在 blob 存储中的 csv 文件,并追加和填充两列。我正在使用 csvhelper 来执行此操作,但在尝试修改实际行时发现它很困难。

我希望这个过程是动态的,因为我将循环遍历容器路径,而且我手头没有所有 csv 文件的结构。

  using (StreamReader reader = new StreamReader(blob.OpenRead()))
    using (CsvReader csv = new CsvReader(reader))
    {
     csv.Read();
     csv.ReadHeader();
     List<string> headers = csv.Context.HeaderRecord.ToList();
     headers.Add("ColA");
     headers.Add("ColB");
     newHeaderContent = string.Join(",", headers);

     // Not sure how to read through the csv and populate the two columns I just appended

    }

using (StreamWriter writer = new StreamWriter(processedblob.OpenWrite()))
    using (CsvWriter csvwriter = new CsvWriter(writer) )
        {
            writer.WriteLine(String.Concat(newHeaderContent));
            //writer code for rows
        }

根据此issue,CsvHelper 不支持这种编辑功能。他还提到您需要 2 个文件,从旧文件读取(然后进行一些更改),然后将更新写入新文件。

下面的代码可以运行并遵循上面的说明:

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.IO;
using System.Text;

namespace AzureBlobConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("your_storage_account", "storage_account_key"), true);
            CloudBlobClient client = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer blobContainer = client.GetContainerReference("f11");
            CloudBlockBlob blob = blobContainer.GetBlockBlobReference("t2.csv");

            //download the .csv file into a text
            string s1 = blob.DownloadText();

            //split the text into an array
            string[] temp = s1.Split('\r');

            // variable s used to store the updated text from .csv
            string s = "";

            //because the last element of the array is redundant data("\n"), so we use temp.Length-1 to abandon it.
            for (int i=0;i<temp.Length-1;i++)
            {
                if (i == 0)
                {
                    temp[i] += ",ColA,ColB"+"\r\n";
                }
                else
                {
                    temp[i] += ",cc,dd"+"\r\n";
                }

                s += temp[i];
            }

            //upload the updated .csv file into azure
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(s));
            blob.UploadFromStream(stream);         

            Console.WriteLine("completed.");
            Console.ReadLine();
        }      

    }
}

测试结果:

更新前:

更新后: