c# - 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
但仍然无济于事。
解决方案
不要使用async void
(事件处理程序除外)。请参阅Async/Await - 异步编程的最佳实践
改为使用public static async Task UploadFromStream
。
您可能会遇到异常并能够追踪错误。
推荐阅读
- php - 如何插入来自我网站的页面和发布者的 ID?
- gradle - Gradle - 配置配置文件报告的输出文件名
- java - 使线程从主线程等待
- android - Android Parcelable - 如何在另一个自定义对象数组中传递自定义对象数组
- r - plotly,无法更改 R 中的单个条形颜色
- angular - 以模态角度显示数据
- php - Woocommerce 过滤器产品使用颜色和类别?
- java - 如何使用 Spring Boot 在控制器中注入 bean?
- r - R ggplot2 geom_smooth - 单调平滑函数
- ios - MKCoordinateRegionMakeWithDistance 的反函数?