Search code examples
c#azureazure-storageazure-blob-storage

How to upload file into Azure Blob Storage using C#?


I have a console app that is written using C# on the top of Core.NET 2.2 framework.

I want to change my storage from local to Azure blob storage. I downloaded WindowsAzure.Storage to connect to my Azure account.

I have the following interface

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

I created the following interface as blob container factory

public interface IBlobContainerFactory
{
    CloudBlobContainer Get();
}

and here is my Azure implementation

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);
    }
}

Then, in my program.cs file I tried the following

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)
    {

    }
}

However, when I use AzureBlobStorage nothing happens. The file does not get written to the storage and no exceptions are thrown!

How can I troubleshoot it? How can I correctly write the file to the storage?

Please note, when I change the configuration in Default:StorageType to Local the file is written locally as expected. But can't get it to write to the Azure blog.


Solution

  • I've followed this article: https://learn.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
                }
            }
        }
    }