我如何在blob存储azure上创建一个csv文件与对象c# .NET核心?



我正在尝试从对象创建CSV文件并将其上传到blob存储。我还希望列具有与对象中的属性相同的名称。(.. NET Core 5.0/c#)

请使用下面的代码:

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace TestKeyVault.Services
{
public class Sample
{ 
public string FirstName { get; set; }
public int Id { get; set; }
public string LastName { get; set; }
}
public class Demo
{
public async Task startAsync()
{
var Friends = new List<Sample> { 
new Sample { FirstName="Naman",LastName="Sinha",Id = 1},
new Sample {FirstName="Naman",LastName="Sinha",Id = 2},  
new Sample {FirstName = "Naman", LastName = "Sinha", Id = 3}
};
string properties = string.Join(",", Friends[0].GetType().GetProperties().Select(i => i.Name));
var info = from member in Friends
let record = string.Join(",", member.GetType().GetProperties().Select(j => j.GetValue(member)))
select record;
var csv = new List<string>
{
properties
};
csv.AddRange(info);
string newPath = Directory.GetCurrentDirectory() + "/Data";
// Determine whether the directory exists.  
if (Directory.Exists(newPath))
Directory.Delete(newPath, true);
Directory.CreateDirectory(newPath);
File.WriteAllLines(newPath + "/FileToBeUploaded.csv", csv);
try
{
CloudStorageAccount account = CloudStorageAccount.Parse("YOUR_STORAGE_ACCOUNT_CONNECTION_STRING");
CloudBlobClient client = account.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference("YOUR_CONTAINER_NAME");
await container.CreateIfNotExistsAsync();
CloudBlockBlob blob = container.GetBlockBlobReference("FileToBeUploaded.csv");
await blob.UploadFromFileAsync(newPath);
Console.WriteLine("File Uploaded!");
}
catch (Exception ex)
{
Console.WriteLine("File could not be downloaded due to: "+ex.Message);
}
}
}
}

代码从样例对象创建CSV文件,并从中生成. CSV文件,然后将其作为blob上传到指定存储帐户的容器中。您只需要更改类和命名空间,并指定Azure存储帐户的连接字符串和容器名称。

相关内容

  • 没有找到相关文章

最新更新