我需要从Azure blob存储中读取csv文件并将内容加载到Azure Table存储中。我成功完成了这一部分并且工作正常。我的代码根据列标题的位置检测csv中的列值,但不基于列名称。所以,我想进一步增强它,以便我的c#代码应该根据标题名称检测列值而不是基于列位置。我探索了字典的选项,但我不确定是否可以使用它来实现。
CSV内容如下所示:
PartitionKey,RowKey,ACE,年龄
TYSE,88010,A1,5
TYSE,88011,A2,4
这是我的代码的核心部分,它执行列分配,如col [0],col [1],col [2]等。
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudBlobClient client = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference("testblobcontainer");
CloudBlob blob = container.GetBlobReference("Test.csv");
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("TestStorageTable");
int lineCount = 0;
using (var stream1 = blob.OpenRead())
{
using (StreamReader reader1 = new StreamReader(stream1))
{
while (!reader1.EndOfStream)
{
lineCount++;
reader1.ReadLine();
}
}
}
using (var stream = blob.OpenRead())
{
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (lineCount > 0)
{
string[] cols = line.Split(',');
TestLiveTbl TestEntity = new TestLiveTbl();
if ((cols[0] != "PartitionKey"))
{
string TempPartitionKey = cols[0].ToString();
string TempRowKey = cols[1].ToString();
TestEntity.TempPartKey = TempPartitionKey;
TestEntity.TempRwKey = TempRowKey;
TestEntity.Ace = cols[2].ToString();
TestEntity.Age = Convert.ToDouble(cols[3]);
TestEntity.AssignPartitionKey();
TestEntity.AssignRowKey();
TestLiveTbl TestEntityIns = RetrieveRecord(table, TempPartitionKey, TempRowKey);
if (TestEntityIns == null)
{
TableOperation tableOperation = TableOperation.Insert(TestEntity);
table.Execute(tableOperation);
Console.WriteLine("Record inserted");
}
}
}
}
}
答案 0 :(得分:-1)
也许你应该从NuGet使用任何库? (例如 - csvHelper:http://joshclose.github.io/CsvHelper/)。
按名称映射可以帮助您)