Quantcast
Channel: briancaos – Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 276

Read and Write blob file from Microsoft Azure Storage with .NET Core

$
0
0

The documentation on the Azure Storage Blobs are a little fuzzy, as the NuGet packages and the approach have changed over time.

The latest NuGet Package is now called:

The concept of blob storages are the same though:

  • You use a connectionstring to connect to an Azure Storage Account.
  • Blob storage is divided into containers. To access a container you need a BlobContainerClient.
  • To access a blob you get a BlobClient from a BlobContainerClient.
  • With the BlobClient you can upload and download blobs.

Blobs can be accessed via an URL, like this:

ENOUGH TALK, SHOW ME THE CODE:

This is an example of a very simple repository that will read, write and delete blobs:

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace MyCode
{
  public class BlobRepository
  {
    private BlobContainerClient _client;

    /// <summary>
    /// Create an instance of blob repository
    /// </summary>
    /// <param name="connectionString">The storage account connection string</param>
    /// <param name="containerName">The name of the container</param>
    public BlobRepository(string connectionString, string containerName)
    {
      _client = new BlobContainerClient(connectionString, containerName);
      // Only create the container if it does not exist
      _client.CreateIfNotExists(PublicAccessType.BlobContainer);
    }

    /// <summary>
    /// Upload a local file to the blob container
    /// </summary>
    /// <param name="localFilePath">Full path to the local file</param>
    /// <param name="pathAndFileName">Full path to the container file</param>
    /// <param name="contentType">The content type of the file being created in the container</param>
    public async Task Upload(string localFilePath, string pathAndFileName, string contentType)
    {
      BlobClient blobClient = _client.GetBlobClient(pathAndFileName);

      using FileStream uploadFileStream = File.OpenRead(localFilePath);
      await blobClient.UploadAsync(uploadFileStream, new BlobHttpHeaders { ContentType = contentType });
      uploadFileStream.Close();
    }

    /// <summary>
    /// Download file as a string
    /// </summary>
    /// <param name="pathAndFileName">Full path to the container file</param>
    /// <returns>Contents of file as a string</returns>
    public async Task<string> Download(string pathAndFileName)
    {
      BlobClient blobClient = _client.GetBlobClient(pathAndFileName);
      if (await blobClient.ExistsAsync())
      {
        BlobDownloadInfo download = await blobClient.DownloadAsync();
        byte[] result = new byte[download.ContentLength];
        await download.Content.ReadAsync(result, 0, (int)download.ContentLength);

        return Encoding.UTF8.GetString(result);
      }
      return string.Empty;
    }

    /// <summary>
    /// Delete file in container
    /// </summary>
    /// <param name="pathAndFileName">Full path to the container file</param>
    /// <returns>True if file was deleted</returns>
    public async Task<bool> Delete(string pathAndFileName)
    {
      BlobClient blobClient = _client.GetBlobClient(pathAndFileName);
      return await blobClient.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots);
    }
  }
}

HOW TO USE IT?

// Create a new repository. Enter the connectionstring and the
// container name in the constructor:
BlobRepository rep = new BlobRepository("YOUR_SECRET_CONNECTIONSTRING","test");

// To upload a file, give a file name from the local disk.
// Add the name of the blob file (notice that the path is in the blob filename
// not, the container name), and the content type of the file to be uploaded
await rep.Upload("d:\\test.json", "blobtest/test.json", "application/json")

// To download a file, enter the path and file name of the blob
// (not including the container name) and the contents is returned as a 
// string
string jsonFile = await rep.Download("blobtest/test.json");

// Deleting the blob is done by entering the path and file of the blob
await rep.Delete("blobtest/test.json");

In the example above, the URL to the created blob will be:

This is just a simple example, but it can easily be modified to uploading streams or downloading binary files.

That’s it. Happy coding.

MORE TO READ:


Viewing all articles
Browse latest Browse all 276

Trending Articles