C# to upload contents of a folder including sub folders to Windows Azure Blob Storage

This is useful if you want to upload stuff like what you would do with an FTP linked to an IIS site:


using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace TestConsoleApp
{

    class Program
    {

        private static CloudBlobContainer _blobContainer = null;
        private static CloudBlobClient _blobClient = null;
        private static CloudStorageAccount _cloudStorageAccount = null;

        static void Main(string[] args)
        {
            _cloudStorageAccount = CloudStorageAccount.Parse("KEY");
            _blobClient = _cloudStorageAccount.CreateCloudBlobClient();
            _blobContainer = _blobClient.GetContainerReference("cdn");
            Console.WriteLine("Connected to Azure...");

            FileInfo[] files = (new DirectoryInfo("ROOTFOLDER")).GetFiles("*.*", SearchOption.AllDirectories);
            Console.WriteLine("Got file list: " + files.Length.ToString());

            for (int i = 0; i < files.Length; i++)
            {
                CloudBlob blob = null;
                string fileName = files[i].FullName.ToLower().Replace("ROOTFOLDER".ToLower(), "").ToLower();
                fileName = fileName.Replace("\\", "/");

                blob = _blobContainer.GetBlobReference(fileName);

                //This is an extension method.
                if (!blob.Exists())
                {
                    Console.WriteLine(i.ToString() + "\\" + files.Length.ToString() + "> Uploading blob: " + fileName);
                    blob.UploadFile(files[i].FullName);
                }
                else
                {
                    Console.WriteLine(i.ToString() + "\\" + files.Length.ToString() + "> Blob exists: " + fileName);
                }
            }

            Console.ReadLine();
        }
    }
}

public static class BlobExtensions
    {
        public static bool Exists(this CloudBlob blob)
        {
            try
            {
                blob.FetchAttributes();
                return true;
            }
            catch (StorageClientException e)
            {
                if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
                {
                    return false;
                }
                else
                {
                    throw;
                }
            }
        }
    }

Comments

Popular posts from this blog

Tutorial: Using Google Cloud Storage from C# and .NET

Late 2008 Macbook only giving 1.5 gb/s speed with 6 gb/s Intel SSD?

Enable Visual Studio to use more than 2GB of memory