【发布时间】:2019-06-27 18:29:40
【问题描述】:
我有一个使用 C# 在 Core.NET 2.2 框架之上编写的控制台应用程序。
我想将我的存储从本地更改为 Azure Blob 存储。我下载了WindowsAzure.Storage 以连接到我的 Azure 帐户。
我有如下界面
public interface IStorage
{
Task Create(Stream stram, string path);
}
我创建了以下接口作为 blob 容器工厂
public interface IBlobContainerFactory
{
CloudBlobContainer Get();
}
这是我的 Azure 实现
public class AzureBlobStorage : IStorage
{
private IBlobContainerFactory ContainerFactory
public AzureBlobStorage(IBlobContainerFactory containerFactory)
{
ContainerFactory = containerFactory;
}
public async Task Create(Stream stream, string path)
{
CloudBlockBlob blockBlob = ContainerFactory.Get().GetBlockBlobReference(path);
await blockBlob.UploadFromStreamAsync(stream);
}
}
然后,在我的program.cs 文件中,我尝试了以下操作
if (Configuration["Default:StorageType"].Equals("Azure", StringComparison.CurrentCultureIgnoreCase))
{
services.AddSingleton(opts => new AzureBlobOptions
{
ConnectionString = Configuration["Storages:Azure:ConnectionString"],
DocumentContainer = Configuration["Storages:Azure:DocumentContainer"]
});
services.AddSingleton<IBlobContainerFactory, DefaultBlobContainerFactory>();
services.AddScoped<IStorage, AzureBlobStorage>();
}
else
{
services.AddScoped<IStorage, LocalStorage>();
}
Container = services.BuildServiceProvider();
// Resolve the storage from the IoC container
IStorage storage = Container.GetService<IStorage>();
// Read a local file
using (FileStream file = File.Open(@"C:\Screenshot_4.png", FileMode.Open))
{
try
{
// write it to the storeage
storage.Create(file, "test/1.png");
}
catch (Exception e)
{
}
}
但是,当我使用 AzureBlobStorage 时,没有任何反应。该文件不会被写入存储并且不会引发异常!
我该如何解决它?如何正确将文件写入存储?
请注意,当我将Default:StorageType 中的配置更改为Local 时,文件会按预期写入本地。但无法将其写入 Azure 博客。
【问题讨论】:
-
你真的在执行 Create 方法吗?看起来您错过了在“storage.Create(file, "test/1.png");"的 program.cs 中等待结果。
-
@Random 确实做到了!我不知道除非我等待,否则代码不会执行。我想没有等待它在后台运行在不同的线程上!
标签: c# azure azure-storage azure-blob-storage