How to Upload and Download File From Azure Blob Storage Using C# and PowerShell

How to Upload and Download File From Azure Blob Storage Using C# and PowerShell

In this Azure tutorial, we will discuss How to Upload and Download File From Azure Blob Storage Using C# and PowerShell.

How to upload file in Azure blob storage (using Azure Portal)

We will discuss how to upload files to Azure blob storage using Azure Portal. Follow the below steps to upload the file.

The first step is to create an Azure storage account and a container in the Azure Portal. Follow the article on How to Create Azure Blob storage to create the Azure storage account and the Blob container.

Now, Navigate to the newly created container you have created above, or use your existing container in the Azure portal.

download file from azure blob storage using url

Then, click on the name of the container, and the container page will open. Click on the Upload button there.

download file from azure blob storage to local folder in c#

On the Upload blob window, click on the Browse button, select the file to be uploaded from the local path of your system, and then click on the Upload button.

download file from azure blob storage using url c#

Now, it will show you the message that Upload completed for the Upload.txt.

download file from blob storage c#

You can see below that the file has been uploaded successfully to my Azure container.

how to download file from azure blob storage using c#

How to Upload and Download File From Azure Blob Storage Using C# and PowerShell

Now, Let’s discuss Upload and Download File From Azure Blob Storage Using C# and PowerShell. Before we start the development activities, We need a storage account, and one container must be created in Azure Portal.

If you do not have the storage account and container created, refer to my article How to Create Azure Blob Storage to create both.

Note: An Azure storage account and the container to be created in the Azure portal is Must before working on the upload and download files from the Blob storage.

You now have the Azure storage account and container created in Azure Portal. So now we will create a console application using C# and Visual Studio 2019 for the below functionality.

  • Upload file in Azure blob storage using C#
  • Download a file from the Azure blob storage using C#

The first step is to create a console application using Visual Studio 2019. To do that, click on File –> New –> Choose Console App (.NET Framework) from the Create a new Project window and click the Next button.

download file from azure blob storage c#

Enter the Project name, select the location, and click the Create button to create the console application.

azcopy download file from blob

The next step is installing the Nuget package to access Azure Storage.

Go to Tools –> NuGet Package Manager –> Manage NuGet Packages for Solution.

error: fatal: from-to argument required, pipeblob (upload) or blobpipe (download) is acceptable

Search for Azure storage and select the Azure.Storage.Blobs. Check the Project name option and then click on the Install button.

download file from azure blob storage c# .net core

Click on the I Accept button on the License Acceptance window.

download blob from azure storage c#

It will install the Nuget package for you now. Use the below namespaces in your Program.cs file

using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

You can see below.

download files from azure blob storage c#

There might be a chance you will get the error. The type or namespace name ‘Azure’ does not exist in the namespace ‘Microsoft’ (are you missing an assembly reference?). To fix this issue, you need to add the below two libraries as a reference to the project.

download file from azure blob storage

Let’s create two methods in the Main() method of the Program.cs file i.e AzureFileUpload() and AzureFileDownload()

  • AzureFileUpload() – Use to upload file files to the Azure blob storage.
  • AzureFileDownload() – Use to download the file from the Azure blob storage.
 static void Main(string[] args)
        {
            AzureDemo azureDemo = new AzureDemo();

            azureDemo.AzureFileUpload("D:\\Upload.txt", "democontainer");
            azureDemo.AzureFileDownload("Upload.txt", "democontainer");

            Console.ReadKey();
        }
powershell download file from blob storage

I have created one class named AzureDemo where the method definitions are present.

How to upload file in Azure blob storage using C#

There are two parameters for the AzureFileUpload() method: The file name to be upload and the Container name.

In the AzureFileUpload() and AzureFileDownLoad() methods, We need to use the Azure storage connection string. So, we need to copy that from the Azure Portal.

Upload file to Azure blob storage c#

To copy that, navigate to the storage account you will use, click on the Access keys, and then copy the connection string as highlighted below and keep it in a notepad. Later on in the code, you can use it.

upload file to azure blob storage c#

Below is the code for the AzureFileUpload().

 public void AzureFileUpload(string fileName, string containerName)
        {
            string myFile,
            myFileName,
            myConnectionString;
            Stream file;

            //Copy and paste the connection string from Azure portal     
            myConnectionString = "DefaultEndpointsProtocol=https;AccountName=sqlvaqrc7kssdx4eus;AccountKey=Coro2SvGOTD+nT3YdaKCrnauz########";

             
            file = new FileStream(fileName, FileMode.Open);

            CloudStorageAccount mycloudStorageAccount = CloudStorageAccount.Parse(myConnectionString);
            CloudBlobClient blobClient = mycloudStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);

            // Check for the container if it exists or not  
            if (container.CreateIfNotExists())
            {

                container.SetPermissionsAsync(new BlobContainerPermissions
                {
                    PublicAccess =
                  BlobContainerPublicAccessType.Blob
                });

            }


            myFile = Path.GetExtension(fileName);
            myFileName = Path.GetFileName(fileName);

            CloudBlockBlob myBlockBlob = container.GetBlockBlobReference(myFileName);
            myBlockBlob.Properties.ContentType = myFile;

            // Upload the file to the blob storage 
            myBlockBlob.UploadFromStreamAsync(file);  

            Console.WriteLine("Upload Completed Successfully!!!!");
        }
how to download files from azure blob storage
how to download file from azure blob storage using powershell

You have copied the Azure storage connection string following the above steps to a notepad. Now is the time to copy and paste it on the below line of code in the AzureFileUpload() method.

//Copy and paste the connection string from the Azure portal
myConnectionString = “Provide the connection string of your storage account”;

FileStream() is used to read the file from the local path of your computer.

file = new FileStream(fileName, FileMode.Open);

The below line of code is used to create the instance of the Storage account.

CloudStorageAccount mycloudStorageAccount = CloudStorageAccount.Parse(myConnectionString);

In the same way, The below line of code is used to create the instance of the Blob Client.

CloudBlobClient blobClient = mycloudStorageAccount.CreateCloudBlobClient();

This line of the code is used to create the instance of the Blob Container.
CloudBlobContainer container = blobClient.GetContainerReference(containerName);

The below lines of code will check if any existing container exists it will create a new container inside the storage account with the mentioned name.

 // Check for the container if it exists or not  
            if (container.CreateIfNotExists())
            {

                container.SetPermissionsAsync(new BlobContainerPermissions
                {
                    PublicAccess =
                  BlobContainerPublicAccessType.Blob
                });

            }

If you run the code, you can see it is uploaded successfully in the democontainer.

how to upload file in azure blob storage using c#

How to upload file in Azure blob storage using PowerShell

We saw above the steps to upload a file in Azure using C# via a console application. Now let’s see how do you upload a file to Azure blob storage using PowerShell. We must follow the steps below to upload the file in Azure blob storage.

Upload blobs from local folder

Sign in to Azure

The first thing is we need to login into Azure with the below cmdlet

PS C:\WINDOWS\system32> Login-AzureRmAccount

Or, you can also use the below PowerShell cmdlet to connect to Azure

PS C:\WINDOWS\system32> Connect-AzAccount

The next step is to get the storage account keys from the Azure portal and assign them to a variable with the below cmdlet

$Keys = "Coro2SvGOTD+nT3YdaKCrnauzWvHMF6BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=="

To get the above key from the Azure portal,

Log in to the Azure portal, navigate to the storage account you will use, click on the Access keys, and then copy the Keys as highlighted below.

How to upload file in azure blob storage using PowerShell

How to Upload Files to Azure File Share using PowerShell

Now, use the below PowerShell cmdlet i.e., the Context, to interact with the Azure storage account with the above AccessKey.

$StorageContext = New-AzureStorageContext -StorageAccountName sqlvaqrc7kssdx4eus -StorageAccountKey $Keys

The below cmdlet is to set the local file path, container name, and Blob along the Storage context.

Set-AzStorageBlobContent -File "D:\Bijay\Upload9.txt" -Container $containerName -Blob "Upload9.txt"  -Context $StorageContext

Now, the Complete PowerShell script is as below.

Login-AzureRmAccount
$Keys = "Coro2SvGOTD+nT3YdaKCrnauzWvHMF6BmuD9PfSKtNJWt6etOMjkwg6KNSQ39zOOQcMpDSjyBKHdALGIg6gZ4Q=="
$StorageContext = New-AzureStorageContext -StorageAccountName sqlvaqrc7kssdx4eus -StorageAccountKey $Keys
$containerName = "democontainer";
Set-AzStorageBlobContent -File "D:\Bijay\Upload9.txt" `
  -Container $containerName `
  -Blob "Upload9.txt" `
  -Context $StorageContext 
upload and download file to azure blob storage using c#

It will ask you to enter the Azure credentials, Enter your credentials, and click the sign-in button.

download files from azure blob storage

Then, it will execute successfully and upload the file to the Azure container.

azure blob storage download file c#

To check that, Navigate to the container in the Azure portal and see the file uploaded successfully.

azure blob storage download file

Download a file from Azure Blob storage (using Azure Portal)

Now, we will discuss how to download files from Azure blob storage using Azure Portal. Follow the below steps to download the file from the Azure blob storage container.

Select the uploaded file which you have done using the above steps. Right-click on the selected file and click the Download link from the pop-up.

powershell download file from azure blob storage using url

Another way is to click on the three dots(…) option and select the Download option from there.

azure function download file from blob storage

Now, the file will download successfully.

How to download a file from the Azure blob storage using C#

There are two parameters for the AzureFileDownload() method. The name of the file to be uploaded and the Container name.

Below is the code for the AzureFileDownload().

public void AzureFileDownload(string fileName, string containerName)
        {
            string mystrconnectionString = "DefaultEndpointsProtocol=https;AccountName=sqlvaqrc7kssdx4eus;AccountKey=Coro2SvGOTD+nT3YdaKCrnauz########";

            CloudStorageAccount mycloudStorageAccount = CloudStorageAccount.Parse(mystrconnectionString);
            CloudBlobClient myBlob = mycloudStorageAccount.CreateCloudBlobClient();

            CloudBlobContainer mycontainer = myBlob.GetContainerReference(containerName);
            CloudBlockBlob myBlockBlob = mycontainer.GetBlockBlobReference(fileName);

            // provide the location of the file need to be downloaded          
            Stream fileupd = File.OpenWrite (@"D:\Bijay\" + fileName);
            myBlockBlob.DownloadToStream(fileupd);

            Console.WriteLine("Download completed Successfully!!!!");
        }
download blob c#

Now, after running the code, I got the below output. It downloaded the file at the specified path.

azure blob download file

How to download file from Azure blob storage using PowerShell

We saw above the steps to download a file from Azure using C# via a console application. Now let’s see how do you download a file from Azure blob storage using PowerShell. We must follow the steps below to download the file from the Azure blob storage.

Download blobs to the local disk

First, we must log in to Azure with the below cmdlet to interact with Azure objects.

PS C:\WINDOWS\system32> Login-AzureRmAccount

Or, you can also use the below PowerShell cmdlet to connect to Azure

PS C:\WINDOWS\system32> Connect-AzAccount

How to Download Blob Contents from an Azure Storage Account using PowerShell

The next step is to get the storage account keys from the Azure portal, and you need to assign it to a variable with the help of the below cmdlet

$Keys = "Coro2SvGOTD+nT3YdaKCrnXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=="

To get the above key from the Azure portal,

You need to log into the Azure portal and go to the storage account from where you are getting the file, click on the Access keys, and then copy the Keys as highlighted below

powershell script to download file from azure blob storage

As mentioned above, use the below PowerShell cmdlet, i.e., the Context, to access the Azure storage account with the above AccessKey.

$StorageContext = New-AzureStorageContext -StorageAccountName sqlvaqrc7kssdx4eus -StorageAccountKey $Keys

The below cmdlet is to provide the local file name that needs to be downloaded, the container name, and the Destination local path where the file needs to be downloaded along with the Storage context.

Get-AzStorageBlobContent -Blob "Upload.txt" -Container $containerName -Destination "D:\Bijay\" ` -Context $StorageContext 

Below is the complete PowerShell script to download the file from the Azure blob storage

Login-AzureRmAccount
$Keys = "Coro2SvGOTD+nT3YdaKCrnauzWvHMF6BmuD9PfSKtNJWt6etOMjkwg6KNSQ39zOOQcMpDSjyBKHdALGIg6gZ4Q=="
$StorageContext = New-AzureStorageContext -StorageAccountName sqlvaqrc7kssdx4eus -StorageAccountKey $Keys
$containerName = "democontainer";
Get-AzStorageBlobContent -Blob "Upload.txt" `
  -Container $containerName `
  -Destination "D:\Bijay\" `
  -Context $StorageContext 
azure storage upload file

How to Download Blob Contents from an Azure Storage Account using PowerShell

It will ask you to provide the Azure credentials, enter your credentials, and click on the Sign in button.

download file from azure blob storage using rest api

You can see above the script executed successfully without any issues.

azcopy command to download file from blob storage

Now, to check that, Navigate to the local path and can see the file downloaded successfully.

upload file to azure blob storage c# .net core

How to Upload Files to Azure Blob Storage Using AzCopy

AzCopy is an excellent command-line tool that helps us to transfer data from and to Azure storage. That also helps to schedule different categories of Backups in Azure storage. It can also help you to copy the data from or to the Azure Stack. You can check out some more information on AzCopy now.

  • Follow the below steps to Upload Files to Azure Blob Storage Using AzCopy.Open the command prompt, navigate to the folder where you have downloaded the AzCopy, and then run the below command to log in.
azcopy login
download from blob storage c#
  • Now, as mentioned above, navigate to https://login.microsoftonline.com/common/oauth2/deviceauth enter the code mentioned on the above screen on the below Pop-up, and then click on the Next button.
upload file to azure file share c#
  • Once you log in successfully, you will see the login succeeded. Now run the below command to create a container in the respective storage account where we will upload the files.
azcopy make “https://<your azure storage accountname>.blob.core.windows.net/<name of your container>”

Example

azcopy make "https://Demoaccount.blob.core.windows.net/test1"

Once you execute the above command, it will show you a message that “Successfully created the resource”

  • The next step is to execute the below command to copy a file from your local machine to your Storage account.
azcopy copy <Your file location in your local path> “https://<your storage account name>.core.windows.net/< your container name>/”

Example

azcopy copy 'C:\azcopy\Testing\testing.txt' 'https://Demoaccount.blob.core.windows.net/test1'

Once you execute the above command, it will show you the message in the command prompt that “Final Job status: Completed”.

  • You can execute the below command to copy all the files to your storage account.
azcopy copy "<Your folder location in your local path>" 'https://<your storage account name>.blob.core.windows.net/<container>' --recursive

Example

azcopy copy "C:\azcopy\Testing2\test" "https://Demoaccount.blob.core.windows.net/test1" --recursive

Once you execute the above command, it will show you the message in the command prompt that “Final Job status: Completed”.

Now, if you log in to the Azure Portal and navigate to the Azure Storage account, you can see that the folder has been created successfully inside the container, and all the files are there.

This is How to Upload Files to Azure Blob Storage Using AzCopy.

You may like the following Azure tutorials:

Conclusion

Well, here in this article, we discussed how to upload file in Azure Blob storage in Azure Portal, How to download a file from Azure Blob storage in Azure Portal, and steps to upload files in Azure Blob storage using C# and PowerShell. Finally, we saw the steps to download a file from the Azure blob storage using C# and PowerShell and how to Upload Files to Azure Blob Storage Using AzCopy. We have created a simple console application using C# and Visualstudion 2019 to interact with the Azure Blob storage. I hope you enjoyed this article!!!!.