How to copy Files from Azure File share to Azure Blob using C#?
3
-
1Please tell us what you have done so far and what problems you are facing.Gaurav Mantri– Gaurav Mantri2016-02-17 14:30:35 +00:00Commented Feb 17, 2016 at 14:30
-
Which kind of programming language you're using?juvchan– juvchan2016-02-17 22:15:35 +00:00Commented Feb 17, 2016 at 22:15
-
I am using C# language to copy Files from Azure File share to Azure Blob.Anil Patel– Anil Patel2016-02-18 07:07:57 +00:00Commented Feb 18, 2016 at 7:07
Add a comment
|
2 Answers
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);
}
2 Comments
Casey Crookston
Excellent. Thank you! I kept getting a "not found" error on the StartCopy line. Your
fileSasUri solved that problem.Anil Patel
@CaseyCrookston, glad this solution work for you. :)
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
Community
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.
Community
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.