1

How to copy Files from Azure File share to Azure Blob using C#?

3
  • 1
    Please tell us what you have done so far and what problems you are facing. Commented Feb 17, 2016 at 14:30
  • Which kind of programming language you're using? Commented Feb 17, 2016 at 22:15
  • I am using C# language to copy Files from Azure File share to Azure Blob. Commented Feb 18, 2016 at 7:07

2 Answers 2

3

Finally got it working.

string rootFolder = "root";

string mainFolder = "MainFolder";

string fileshareName = "testfileshare";

string containerName = "container";

string connectionString = "Provide StorageConnectionString here";

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
        CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

        // Create a new file share, if it does not already exist.
        CloudFileShare share = fileClient.GetShareReference(fileshareName);
        share.CreateIfNotExists();

        // Create a new file in the root directory.

        CloudFileDirectory rootDir = share.GetRootDirectoryReference();

        CloudFileDirectory sampleDir = rootDir.GetDirectoryReference(rootFolder);


        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference(containerName.ToLower());
        container.CreateIfNotExists();

        foreach (var Files in sampleDir.ListFilesAndDirectories())
        {
            char strdelim = '/';
            string path = Files.Uri.ToString();
            var arr = Files.Uri.ToString().Split(strdelim);
            string strFileName = arr[arr.Length - 1];

            Console.WriteLine("\n" + strFileName);

            CloudFile sourceFile = sampleDir.GetFileReference(strFileName);

            string fileSas = sourceFile.GetSharedAccessSignature(new SharedAccessFilePolicy()
            {
                // Only read permissions are required for the source file.
                Permissions = SharedAccessFilePermissions.Read,
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24)
            });

            Uri fileSasUri = new Uri(sourceFile.StorageUri.PrimaryUri.ToString() + fileSas);

            string blob = mainFolder + "\\" + strFileName;

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(blob);

            blockBlob.StartCopy(fileSasUri);

        }
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent. Thank you! I kept getting a "not found" error on the StartCopy line. Your fileSasUri solved that problem.
@CaseyCrookston, glad this solution work for you. :)
0
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.File;
using OC3.Core.Model.Server;

namespace OC3.API.Controllers
{
    [Route("v1/desktop/[controller]")]
    [ApiController]
    [EnableCors("AllowOrigin")]
    public class DownloadController : Controller
    {
        private readonly IConfiguration _configuration;

        public DownloadController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        // code added by Ameer for downloading the attachment from shipments
        [HttpPost("Attachment")]
        public async Task<ActionResult> ActionResultAsync(RequestMessage requestMessage)
        {
            ResponseMessage responseMessage = new ResponseMessage();

            responseMessage.resultType = "Download";

            string filepath = string.Empty;
            if (requestMessage.parameters[0] != null && requestMessage.parameters[0].name != null)
                filepath = requestMessage.parameters[0].name.ToString();
            try
            {
                if (!string.IsNullOrEmpty(filepath))
                {
                    responseMessage.totalCount = 1;

                    string shareName = string.Empty;        

                    filepath = filepath.Replace("\\", "/");
                    string fileName = filepath.Split("/").Last();
                    if (filepath.Contains("/"))
                    {
                        //Gets the Folder path of the file.
                        shareName = filepath.Substring(0, filepath.LastIndexOf("/")).Replace("//", "/"); 
                    }
                    else
                    {
                        responseMessage.result = "File Path is null/incorrect";
                        return Ok(responseMessage);
                    }

                    string storageAccount_connectionString = _configuration["Download:StorageConnectionString"].ToString();
                    // get file share root reference
                    CloudFileClient client = CloudStorageAccount.Parse(storageAccount_connectionString).CreateCloudFileClient();
                    CloudFileShare share = client.GetShareReference(shareName);

                    // pass the file name here with extension
                    CloudFile cloudFile = share.GetRootDirectoryReference().GetFileReference(fileName);

                    var memoryStream = new MemoryStream();
                    await cloudFile.DownloadToStreamAsync(memoryStream);
                    responseMessage.result = "Success";

                    var contentType = "application/octet-stream";

                    using (var stream = new MemoryStream())
                    {
                        return File(memoryStream.GetBuffer(), contentType, fileName);
                    }
                }
                else
                {
                    responseMessage.result = "File Path is null/incorrect";
                }
            }
            catch (HttpRequestException ex)
            {
                if (ex.Message.Contains(StatusCodes.Status400BadRequest.ToString(CultureInfo.CurrentCulture)))
                {
                    responseMessage.result = ex.Message;
                    return StatusCode(StatusCodes.Status400BadRequest);
                }
            }
            catch (Exception ex)
            {
                // if file folder path or file is not available the exception will be caught here
                responseMessage.result = ex.Message;
                return Ok(responseMessage);
            }

            return Ok(responseMessage);
        }
    }
}

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.