Home > Azure > [Code Snippet] Upload file to Azure blob – C#

[Code Snippet] Upload file to Azure blob – C#

In this article I am going to provide details and code snippets on how to upload attachment to Azure blob storage from console application.

Prerequisites: 

Below are the prerequisites to run the code snippet and upload the file

  • Azure subscription:You need an Azure subscription as the first  step.
    • You can spin up 30 days trail Azure subscription. Click here
    • Note: You need to share valid credit card details to complete the subscription and you will be charged 2 INR.
  • Storage Account:Add a storage account

Azure - Storage Account

  • Container:
    • Add a Container
    • Copy the Container Name.

Azure - Storage Account - Containers

  • Access Keys:Need the ‘Key’ to connect to Azure Blob from your C# console.
    • Copy and keep below 2 values as shown in screenshot
      • Storage Account Name
      • Key 1

Azure - Storage Account - Keys

  • Nuget package:Add below nuget packages to your console project
      • Microsoft.WindowsAzure.Storage

C# Code Snippet:

// Namespaces

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;

private static void AddFileToBlob(){
var accountName = “{Storage Account Name}“; // Refer Prerequisites for value
var keyValue = “{key 1}“; // Refer Prerequisites for value
var useHttps = true;
var connValid = true;

// Establish connection to Azure

var storageCredentials = new StorageCredentials(accountName, keyValue);
var storageAccount = new CloudStorageAccount(storageCredentials, useHttps);
var blobConString = storageAccount.ToString(connValid);

// Retrieve storage account from connection string.
storageAccount = CloudStorageAccount.Parse(blobConString);

// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Set container name
CloudBlobContainer container = blobClient.GetContainerReference(“{Container Name}“); // Refer Prerequisites for value

// Set your blob name; It can be anything
CloudBlockBlob blockBlob = container.GetBlockBlobReference(“{Your desired blob name}“);

// Set your file path which you want to upload to blob
using (var fileStream = System.IO.File.OpenRead(@”D:\ABC.PNG”)) {
blockBlob.UploadFromStream(fileStream);
}

Console.WriteLine(“File added to Blob!!!”);
}

🙂

Advertisement
Categories: Azure Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: