gpt4 book ai didi

c# - 将文件即时上传到 Azure Blob

转载 作者:行者123 更新时间:2023-11-30 14:09:17 24 4
gpt4 key购买 nike

我正在尝试创建一个文件并使用 CloudBlockBlob.UploadFromStreamAsync() 方法将其放入 blob 中。

代码如下:

    private async void CreateCsvFile(int recId)
{
using (var csvFile = new StreamWriter())
{
for (int i = 1; i <= recId; ++i)
{
Ad ad = db.Ads.Find(i);
if (ad != null)
{
string rec = String.Format("{0}, {1}, {2}, {3}, {4}", ad.Title, ad.Category, ad.Price, ad.Description, ad.Phone);
csvFile.WriteLine(rec);
}
}

csvFile.Flush();
string blobName = Guid.NewGuid().ToString() + recId.ToString() + ".csv";
CloudBlockBlob fileBlob = fileBlobContainer.GetBlockBlobReference(blobName);
await fileBlob.UploadFromStreamAsync((Stream) csvFile);
}
}

更新了新要求:

// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}

问题:

  1. 文件是即时创建的,而不是从客户端上传的。这是正确的做法吗?
  2. 编译器提示 2 个问题:1) StreamWriter 的 Ctor 不接受 0 参数; 2) 类型 'StreamWriter' 无法转换为 'Stream'(我在这里转换是因为 UploadFromStreamAsync() 方法将 Stream 类型作为参数)。如何修复编译器错误?谢谢!

最佳答案

所以我之前有一个到 blob 的流,如下所示:

public async Task<Stream> GetWriteStreamAsync(string storagePath, string contentType)
{
var blockBlob = blobContainer.GetBlockBlobReference(storagePath);
blockBlob.Properties.ContentType = contentType;
CloudBlobStream bb = await blockBlob.OpenWriteAsync();
return bb;
}

现在你可以

using(var str = await GetWriteStreamAsync("someBlobName.csv", "text/csv"))
using(var csvFile = new StreamWriter(str))
{
for (int i = 1; i <= recId; ++i)
{
Ad ad = db.Ads.Find(i);
if (ad != null)
{
string rec = String.Format("{0}, {1}, {2}, {3}, {4}",
ad.Title,
ad.Category,
ad.Price,
ad.Description,
ad.Phone);
csvFile.WriteLine(rec);
}
}
csvFile.Flush();
}

关于c# - 将文件即时上传到 Azure Blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com