TIP
💡 Learn more : Azure storage account overview (opens new window).
# Uploading and Downloading a Stream into an Azure Storage Blob
Azure Storage is described as a service that provides storages that is available, secure, durable, scalable, and redundant. Azure Storage consists of 1) Blob storage, 2) File Storage, and 3) Queue storage. In this post, we'll take a look at how to upload and download a stream into an Azure Storage Blob with C#. In previous posts, I've described how to create an Azure Storage account through the Portal and recently how to create an Azure Storage Blob Container through C#.
Go ahead and open the Azure Portal and navigate to the Azure Storage account that we worked with previously and open the C# Console application as we'll be using it shortly.
# Upload a File
Now that we've created the Azure Storage Blob Container, we'll upload a file to it. We'll build off our last code snippet and add the following lines of code to upload a file off our local hard disk:
static void Main(string[] args)
{
string connectionString = CloudConfigurationManager.GetSetting("StorageConnection");
BlobContainerClient container = new BlobContainerClient(connectionString, "images-backup");
container.CreateIfNotExists(PublicAccessType.Blob);
//lines modified
var blockBlob = container.GetBlobClient("mikepic.png");
using (var fileStream = System.IO.File.OpenRead(@"c:\mikepic.png"))
{
blockBlob.Upload(fileStream);
}
//lines modified
Console.ReadLine();
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
If we switch over to our Storage Account and navigate inside the container, we'll see our new file has been added:
# Download a File
Now that we've uploaded a file to the Azure Storage Blob Container, we'll download a file from it. We'll build off our last code snippet and add the following lines of code to download a file off our local hard disk and give it new name:
static void Main(string[] args)
{
string connectionString = CloudConfigurationManager.GetSetting("StorageConnection");
BlobContainerClient container = new BlobContainerClient(connectionString, "images-backup");
container.CreateIfNotExists(PublicAccessType.Blob);
//lines modified
var blockBlob = container.GetBlobClient("mikepic.png");
using (var fileStream = System.IO.File.OpenWrite(@"C:\Users\mbcrump\Downloads\mikepic-backup.png"))
{
blockBlob.DownloadTo(fileStream);
}
//lines modified
Console.ReadLine();
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Note that are now using the OpenWrite method and specifying a new name. We are also taking advantage of the DownloadTo method. If we run the application, our new file should be in the downloads folder.