How to programmatically upload files to Azure Storage (File Share)
Describes how to save files to Azure Storage.
Azure Storage type uses file sharing (not blob).
Advance preparation
Create storage environment on Azure portal
–Create a storage account
–Create a File Share from the created storage account
Install Azure.Storage library
Install the following from Manage NuGet Packages
- Azure.Storage.Common
- Azure.Storage.Files.Shares
program
using System.IO;
using Azure.Storage;
using Azure.Storage.Files.Shares;
public class SampleClass
{
public void Upload()
{
///Get information from your Azure storage account and configure
string accountName = "{Get the account name from the Azure portal site.}";
string accessKey = "{Get the access key from the Azure portal site.}";
Uri serverurl = new Uri(@"{Get the URL from the Azure portal.}") ;
///Upload destination(azure side)
string azureDirectoryPath = @"{Destination(azure side)Specify the directory of}" ;
string azureFileName = "{Specify the file name to save}";
///Upload target(Local side)
string localDirectoryPath = @"{Upload target(Local side)Specify the directory of}";
string localFileName = "{Upload target(Local side)Specify the file name of}";
//SSL communication permission setting
//If you don't do this, SSL(https)An error occurs in communication.
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
try
{
//Preparing to connect to Azure: Setting connection information
StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accessKey);
//Connect to Azure
ShareClient share = new ShareClient(serverurl , credential);
ShareDirectoryClient directory = share.GetDirectoryClient(azureDirectoryPath);
//Upload destination(azure side)Create if there is no folder in.
directory.CreateIfNotExists();
//Upload destination(azure side)Create a file instance in.
ShareFileClient file = directory.GetFileClient(azureFileName);
//Delete any file with the same name
file.DeleteIfExists();
//Open the Local file to be uploaded. It is easy to get binary information by opening it with FileStream type.
FileStream stream = File.OpenRead( Path.Combine(localDirectoryPath , localFileName ) );
//Upload destination(azure side)Inject binary information into a file instance
file.Create(stream.Length);
file.UploadRange(new Azure.HttpRange(0, stream.Length),stream);
//Free local files
stream.Dispose();
}
catch(Exception ex)
{
System.Console.WriteLine(ex.Message);
return;
}
}
}
Postscript
–It seems that the recommended library for accessing storage has changed from Windows Azure.Storage to Azure.Storage. Since there was no sample using Azure.Storage, I posted it as a memo.
–There was a fluctuation in the notation of [File Share], [File Share], and [File Service] in Azure. (As of September 30, 2020) It looks good to interpret it as a synonym.