Skip to content

How to use

Stefan edited this page Feb 14, 2023 · 2 revisions

Inject

With only one storage account

Inject the default storage account:

   public MyClass(IAzureBlobStorageService storageService)
   {
   }

With multiple storage accounts

Inject using the generic implementation and specify a factory:

   public MyClass(IAzureBlobStorageService<IMyClientFactory> storageService)
   {
   }

Provided methods

string GetStorageAccountName()

Returns the name of the storage account. This is the name configured in the connection string.

IAsyncEnumerable GetContainersAsync();

Returns a list of containers that are currently configured in the storage account

Task CreateContainerIfNotExistsAsync(string containerName = null);

Creates a container with the specified name or if no container name is specified the default container.

Task DeleteContainerAsync(string containerName = null);

Deletes a specified container or if no container name is specified the default container.

IAsyncEnumerable ListBlobsInContainerAsync(string containerName = null);

Lists all files inside the specified container or if not specified the default container.

Usage:

   var files = await _service.ListBlobsInContainerAsync(containerName).ToListAsync(); // with nuget package System.Linq.Async

   foreach (var f in files)
   {
       Console.WriteLine(f.Name);
   }

Fields:

    public class BlobInfoContract
    {
        public string Name { get; set; }

        public string BlobType { get; set; }

        public string ContentEncoding { get; set; }

        public string ContentType { get; set; }

        public long? Size { get; set; }

        public DateTimeOffset? DateCreated { get; set; }

        public string AccessTier { get; set; }
    }

Task GetBlobContentsAsync(string blobName, string containerName = null);

Get the blob content. If not container name is specifeid the default container is used.

Usage:

   var file = await _service.GetBlobContentsAsync("file.txt", containerName);
   var azureStream = file.Content;

   await using var outputStream = File.Create("file.txt");
   CopyStream(azureStream, outputStream);

Note: The BlobContract contains all fields of BlobInfoContract + Content with a read stream.

Task UploadBlobAsync(string blobName, string contentType, Stream content, string containerName = null);

Upload a file to the specified container or the default container if not specified.

Usage:

   await _service.CreateContainerIfNotExistsAsync(containerName);

   await using var inputStream = new FileStream("file.txt", FileMode.Open, FileAccess.Read);
   await _service.UploadBlobAsync("file.txt", "text/plain", inputStream, containerName);

Task DeleteBlobAsync(string blobName, string containerName = null);

Deletes a file from the specified container or the default container if not specified.