Azure Blob存储未上传

时间:2018-11-02 12:55:46

标签: c# azure .net-core azure-storage

我正在尝试将文本文件从流上载到.Net Core中的AzureBlobStorage,但似乎无声地失败了。我正在从数据库中读取数据,然后使用MemoryStream将其写入StreamWriter。在我上传到BlobStorage时,Stream的长度为7147,所以我知道其中有数据。

这是我上传文件的代码:

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;
    }
}

致电者:

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();
}

我没有进入Catch块,所以我认为没有遇到任何异常,但是当我检查Storage时,那里什么都没有。该应用程序运行无误。

我什至尝试使用byte[] bytes = stream.ToArray()blockBlob.UploadFromByteArrayAsync,但仍然无济于事。

2 个答案:

答案 0 :(得分:2)

请勿使用async void(事件处理程序除外)。参见Async/Await - Best Practices in Asynchronous Programming

改为使用public static async Task UploadFromStream

您可能会得到一个异常,并能够找到错误。

答案 1 :(得分:0)

为什么Task.Run(() => StorageService.UploadFromStream($"logfile_{DateTime.Today:s}", memoryStream)).Wait();以及为什么不能像下面这样await,只要您将方法签名更改为public static async Task UploadFromStream(...(如在另一个答案中所建议的那样)

await StorageService.UploadFromStream($"logfile_{DateTime.Today:s}", memoryStream)