I am trying to create a file and put it in blob with CloudBlockBlob.UploadFromStreamAsync()
method.
Here's the code:
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);
}
}
Updated with a new requirement:
// 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();
}
}
Questions:
- The file is created on the fly instead of being uploaded from client. Is this the correct way to do that?
- Compiler complains about 2 problems: 1) Ctor of StreamWriter does not take 0 argument; 2) Type 'StreamWriter' can't be converted to 'Stream' (I am casting here because
UploadFromStreamAsync()
method takes Stream type as parameter). How do I fix the compiler errors? Thanks!