【问题标题】:How to upload file into Azure Blob Storage using C#?如何使用 C# 将文件上传到 Azure Blob 存储?
【发布时间】: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


【解决方案1】:

我关注了这篇文章:https://docs.microsoft.com/en-us/dotnet/api/overview/azure/storage?view=azure-dotnet

public interface IStorage
{
    Task Create(Stream stream, string path);
}

public class AzureBlobStorage : IStorage
{
    public async Task Create(Stream stream, string path)
    {
        // Initialise client in a different place if you like
        string storageConnectionString = "DefaultEndpointsProtocol=https;"
                    + "AccountName=[ACCOUNT]"
                    + ";AccountKey=[KEY]"
                    + ";EndpointSuffix=core.windows.net";

        CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString);
        var blobClient = account.CreateCloudBlobClient();

        // Make sure container is there
        var blobContainer = blobClient.GetContainerReference("test");
        await blobContainer.CreateIfNotExistsAsync();

        CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(path);
        await blockBlob.UploadFromStreamAsync(stream);
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Put your DI here
        var storage = new AzureBlobStorage();

        // Read a local file
        using (FileStream file = File.Open(@"C:\cartoon.PNG", FileMode.Open))
        {
            try
            {
                // Pattern to run an async code from a sync method
                storage.Create(file, "1.png").ContinueWith(t =>
                {
                    if (t.IsCompletedSuccessfully)
                    {
                        Console.Out.WriteLine("Blob uploaded");
                    }
                }).Wait();
            }
            catch (Exception e)
            {
                // Omitted
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    你可能想看看这个线程。 我为类似问题添加了一些答案

    ASP.NET Web API Azure Blob Storage Unstructured

    【讨论】:

    • 编译错误:“任务”不包含“IsCompletedSuccessfully”的定义,并且找不到接受“Task”类型的第一个参数的可访问扩展方法“IsCompletedSuccessfully”(您是否缺少 using 指令还是程序集参考?)
    猜你喜欢
    • 2019-08-13
    • 2021-03-05
    • 2017-01-22
    • 2017-01-24
    • 2017-08-19
    • 2021-06-20
    • 2019-07-10
    • 1970-01-01
    相关资源
    最近更新 更多