Home > database >  how to upload files with its original folder structure in blob storage?
how to upload files with its original folder structure in blob storage?

Time:03-22

below code will upload files to blob storage

// intialize BobClient 
            Azure.Storage.Blobs.BlobClient blobClient = new Azure.Storage.Blobs.BlobClient(
                connectionString: connectionString, 
                blobContainerName: "mycrmfilescontainer", 
                blobName: "sampleBlobFileTest");
             
            // upload the file
            blobClient.Upload(filePath);

but how to upload all files and maintain its folder structure as well?

I have site folder which includes all html files images css folder and inside that relative files of website.

I want to upload that complete site folder over on blob storage kindly suggest approch.

CodePudding user response:

Please take a look at the code below:

using System.Threading.Tasks;
using System.IO;
using Azure.Storage.Blobs.Specialized;

namespace SO71558769
{
    class Program
    {

        private const string connectionString = "connection-string";
        
        private const string containerName = "container-name";

        private const string directoryPath = "C:\temp\site\";
        
        static async Task Main(string[] args)
        {
            var files = Directory.GetFiles(directoryPath, "*.*", SearchOption.AllDirectories);
            for (var i=0; i<files.Length; i  )
            {
                var file = files[i];
                var blobName = file.Replace(directoryPath, "").Replace("\\", "/");
                BlockBlobClient blobClient = new BlockBlobClient(connectionString, containerName, blobName);
                using (var fs = File.Open(file, FileMode.Open))
                {
                    await blobClient.UploadAsync(fs);
                }
            }
        }
    }
}

Essentially the idea is to get the list of all files in the folder and then loop over that collection and upload each file.

To get the blob name, you would simply find the directory path in the file name and replace it with an empty string to get the blob name (e.g. if full file path is C:\temp\site\html\index.html, then the blob name would be `html\index.html).

If you are on Windows, then you would further need to replace \ delimiter with / delimiter so that you get the final blob name as html/index.html.

  • Related