使用csvhelper操作csv结构和内容

时间:2019-01-18 14:11:24

标签: c# csv azure-storage-blobs 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
        }

1 个答案:

答案 0 :(得分:0)

根据此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();
        }      

    }
}

测试结果:

更新前:

enter image description here

更新后:

enter image description here