如何为MemoryStream中写入的内容提供*.csv扩展名



我正在开发一个Azure函数,用于从自定义对象列表创建CSV文件,对其进行gzip处理并将其上传到Azure存储容器,代码为:

var blobServiceClient = new BlobServiceClient("My connection string");
var containerClient = blobServiceClient.GetBlobContainerClient("My container name");
var config = new CsvConfiguration(CultureInfo.CurrentCulture) { Delimiter = ";", Encoding = Encoding.UTF8 };
var list = new List<FakeModel>
{
new FakeModel { Field1 = "A", Field2 = "B" },
new FakeModel { Field1 = "C", Field2 = "D" }
};
await using var memoryStream1 = new MemoryStream();
await using var streamWriter = new StreamWriter(memoryStream1);
await using var csvWriter = new CsvWriter(streamWriter, config);
await csvWriter.WriteRecordsAsync(list);
await csvWriter.FlushAsync();
memoryStream1.Position = 0;
await using var memoryStream2 = new MemoryStream();
await using var zip = new GZipStream(memoryStream2, CompressionMode.Compress, true);
await memoryStream1.CopyToAsync(zip);
memoryStream2.Position = 0;
var blockBlob = containerClient.GetBlockBlobClient("test.csv.gz");
await blockBlob.UploadAsync(memoryStream2);

它有效。当我从云中下载gzip进行检查时,很明显我会发现该文件的名称是正确的,所以它显示为一个GZ文件,名称为test.csv.gz,但当我下载它并用提取器打开它时,我会发现它里面的CSV文件有点奇怪,比如test.csv-3,我的计算机无法打开。当然,我需要它是一个有效的*.csv文件。这里的问题是,使用内存流,我只能为blob提供一个名称,而不能为内部CSV文件提供名称。我该怎么做?请记住,我希望使用内存流来简化Azure函数的本地存储。你能帮我吗?

关于这个问题,请参考以下代码

var blobServiceClient = new BlobServiceClient("My connection string");
var containerClient = blobServiceClient.GetBlobContainerClient("My container name");
var config = new CsvConfiguration(CultureInfo.CurrentCulture) { Delimiter = ";", Encoding = Encoding.UTF8 };
var list = new List<FakeModel>
{
new FakeModel { Field1 = "A", Field2 = "B" },
new FakeModel { Field1 = "C", Field2 = "D" }
};
await using var memoryStream1 = new MemoryStream();
await using var streamWriter = new StreamWriter(memoryStream1);
await using var csvWriter = new CsvWriter(streamWriter, config);
await csvWriter.WriteRecordsAsync(list);
await csvWriter.FlushAsync();
memoryStream1.Position = 0;
var options = new BlockBlobOpenWriteOptions
{
HttpHeaders = new BlobHttpHeaders
{
ContentType = "application/gzip",
},
};
await using var outStream= await containerClient.GetBlockBlobClient("test.csv.gz").OpenWriteAsync(true,options);
await using var zip = new GZipStream(outStream, CompressionMode.Compress, true);

await memoryStream1.CopyToAsync(zip);
await using var input = await containerClient.GetBlockBlobClient("test.csv.gz").OpenReadAsync();
await using var file = File.Create("<file path>");
await using var zip1 = new GZipStream(input, CompressionMode.Decompress, true);
await zip1.CopyToAsync(file);

相关内容

  • 没有找到相关文章

最新更新