Upload or download file from Azure Blob Storage with progress percentage c#
We extensively use Azure Blob Storage to upload and download files. When we are uploading or downloading a file, reporting back the progress percentage to the end-user becomes an important aspect of our programming task. In this article, we are going to see how it can be achieved using the Azure Blob Storage SDK v12 in c#.
If you are getting started with Blob Storage SDK v12 or looking out to understand the basic operations of blob storage using the v12 SDK then kindly refer to the article at https://www.craftedforeveryone.com/beginners-guide-and-reference-to-azure-blob-storage-sdk-v12-dot-net-csharp/
NuGet Package
To work with SDK v12 make sure to download the NuGet package Azure.Storage.Blob from https://www.nuget.org/packages/Azure.Storage.Blobs
Source Code
You can clone the full working code from GitHub at https://github.com/kaarthikin/upload_download_azure_blob_with_progress_percentage_in_csharp.
The code connects to the local storage emulator and pushes the files to an already existing container.
Code execution preview with Blob upload and download progress percentage
Upload File to Azure Blob Storage with Progress Percentage
Retrieving the file uploaded progress is straight forward and simple with Blob Storage SDK v12. The BlobClient.Upload() accepts IProgress as a method input. The IProgress object can be used to get the total bytes that have been uploaded so far to the blob storage.
Step 1: Initialize the class Progress of type long
var progressHandler = new Progress<long>();
Step 2: Register a function to the ProgressChanged event of the class Progress
progressHandler.ProgressChanged += UploadProgressChanged;
Step 3: Inside the function that is registered with the Progress class calculate the total file size uploaded by using the formula.
(bytesUploadedSoFar/totalFileSizeInBytes)*100
Note: The value of the ProgressChanged event is of type long. We need to convert the value to double before dividing it with total file size, else the result value returned will be always 0
Step 4: Pass the object of Progress<long> to BlobClient.Upload() method
var blob = new BlobClient(connectionString, containerName, file.Name); blob.Upload(fileToUploadPath, progressHandler: progressHandler); //Make use to pass the progress handler here
Source code to upload a file with progress percentage
public void UploadBlob(string fileToUploadPath) { var file = new FileInfo(fileToUploadPath); uploadFileSize = file.Length; //Get the file size. This is need to calculate the file upload progress //Initialize a progress handler. When the file is being uploaded, the current uploaded bytes will be published back to us using this progress handler by the Blob Storage Service var progressHandler = new Progress(); progressHandler.ProgressChanged += UploadProgressChanged; var blob = new BlobClient(connectionString, containerName, file.Name); //Initialize the blob client blob.Upload(fileToUploadPath, progressHandler: progressHandler); //Make sure to pass the progress handler here } private double GetProgressPercentage(double totalSize,double currentSize) { return (currentSize / totalSize) * 100; } private void UploadProgressChanged(object sender, long bytesUploaded) { //Calculate the progress and update the progress bar. //Note: the bytes uploaded published back to us is in long. In order to calculate the percentage, the value has to be converted to double. //Auto type casting from long to double happens here as part of function call Console.WriteLine(GetProgressPercentage(uploadFileSize, bytesUploaded)); }
Download File from Azure Blob Storage with Progress Percentage
Unlike the upload method accepting an object of type Progress<long> to report the total bytes uploaded, we do not have a direct method in case of download to get the progress. The workaround steps that have to be followed are below
Step 1: Get the download Stream object of the file from Blob Storage. We shall call it as the source stream
Step 2: Get the stream object to the path where the file as to be saved. We shall call it as destination stream
Step 3: Read bytes as a chunk of data from the source stream and write it to the destination stream in a loop.
Step 4: Sum up the bytes read in each iteration of the loop to calculate the progress percentage.
Step 5: Apply the progress percentage formula to report the progress.
public void DownloadBlob(string blobPath,string pathToDownload) { //Get the blob client instance and call the method Download(). //Note: At this line we are not download the file, we are just getting the download stream of the file with additional metadata to download. var blobToDownload = new BlobClient(connectionString, containerName, blobPath).Download().Value; //Step 1 var outputFile = File.OpenWrite(pathToDownload); //Step 2 var downloadBuffer = new byte[81920]; //Choose an appropriate buffer size int bytesRead; int totalBytesDownloaded=0; //Read(Download) the file in bytes while((bytesRead=blobToDownload.Content.Read(downloadBuffer,0,downloadBuffer.Length))!=0) //Step 3 { outputFile.Write(downloadBuffer, 0, bytesRead); // Write the download bytes from source stream to destination stream. //Step 3 totalBytesDownloaded += bytesRead;//Increment the total downloaded counter. This is used for percentage calculation //Step 4 Console.WriteLine(GetProgressPercentage(blobToDownload.ContentLength, totalBytesDownloaded)); //Step 5 } //Close both the source and destination stream blobToDownload.Content.Close(); outputFile.Close(); } private double GetProgressPercentage(double totalSize,double currentSize) { return (currentSize / totalSize) * 100; }