即时上传文件到Azure Blob

itn*_*ice 3 c# azure-storage-blobs

我正在尝试创建一个文件并使用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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

更新了新要求:

// 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();
   }
}
Run Code Online (Sandbox Code Playgroud)

问题:

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

spe*_*der 7

所以我以前有一个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;
}
Run Code Online (Sandbox Code Playgroud)

所以现在你可以

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();
}
Run Code Online (Sandbox Code Playgroud)