I'm trying to upload a text file from a stream to AzureBlobStorage in .Net Core but it seems to be failing silently. I am reading data from a database and writing it into a MemoryStream
using a StreamWriter
. At the point I am uploading to BlobStorage, the Stream
has a Length of 7147 so I know it's got data in it.
Here's my code to upload the file:
public static async void UploadFromStream(string fileName, Stream stream, string fileExtenstion = "txt")
{
var storageAccount = CloudStorageAccount.Parse(_connectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("logs");
// By this point, I have a reference to my `logs` container which exists
var blockBlob = container.GetBlockBlobReference($"{fileName}.{fileExtenstion}");
try
{
stream.Position = 0;
await blockBlob.UploadFromStreamAsync(stream);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Called by:
var memoryStream = new MemoryStream();
using (var writer = new StreamWriter(memoryStream))
{
while (reader.Read())
{
writer.WriteLine(
$"[{reader["Timestamp"]}][{reader["Level"].ToString().ToUpper()}] :: {reader["Message"]}{(!string.IsNullOrWhiteSpace(reader["Exception"].ToString()) ? " -- " + reader["Exception"] : "")}");
}
Task.Run(() => StorageService.UploadFromStream($"logfile_{DateTime.Today:s}", memoryStream)).Wait();
}
I don't get inside my Catch block so I don't think I'm hitting any Exceptions, but when I check my Storage, there's nothing there. The application runs through with no errors.
I have even tried using byte[] bytes = stream.ToArray()
and using the blockBlob.UploadFromByteArrayAsync
but still to no avail.
Don't use async void
(except for Event handlers). See Async/Await - Best Practices in Asynchronous Programming
Use public static async Task UploadFromStream
instead.
You will probably get an exception and be able to track down the error.