0

如何使用 C# 将文件从 Azure 文件共享复制到 Azure Blob?

4

2 回答 2

3

终于让它工作了。

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);

        }
于 2016-02-18T10:34:19.117 回答
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);
        }
    }
}
于 2021-10-12T10:40:59.737 回答