如何使用C#将文件上传到Azure Blob存储?

时间:2019-02-04 00:30:34

标签: c# azure azure-storage azure-storage-blobs azure-blob-storage

我在Core.NET 2.2框架的顶部有一个使用C#编写的控制台应用程序。

我要将存储从本地更改为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博客。

2 个答案:

答案 0 :(得分: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
            }
        }
    }
}

答案 1 :(得分:0)

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

ASP.NET Web API Azure Blob Storage Unstructured