首页 > 解决方案 > Azure Blob 存储未上传

问题描述

我正在尝试将文本文件从流上传到 .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 块,所以我认为我没有遇到任何异常,但是当我检查我的存储时,那里什么都没有。应用程序运行没有错误。

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

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

解决方案


不要使用async void(事件处理程序除外)。请参阅Async/Await - 异步编程的最佳实践

改为使用public static async Task UploadFromStream

您可能会遇到异常并能够追踪错误。


推荐阅读