繁体   English   中英

Azure Blob 存储未上传

[英]Azure Blob Storage not Uploading

我正在尝试将流中的文本文件上传到 .Net Core 中的 AzureBlobStorage,但它似乎无声无息地失败了。 我正在从数据库中读取数据并使用StreamWriter将其写入MemoryStream 在我上传到 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 byte[] bytes = stream.ToArray()并使用blockBlob.UploadFromByteArrayAsync但仍然无济于事。

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

改用public static async Task UploadFromStream

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

为什么Task.Run(() => StorageService.UploadFromStream($"logfile_{DateTime.Today:s}", memoryStream)).Wait(); 为什么你不能像下面那样await它,前提是你将方法签名更改为public static async Task UploadFromStream(...正如在另一个答案中已经建议的那样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM