将文件从 Azure 文件共享复制到 Azure Blob 的 C# 代码
Posted
技术标签:
【中文标题】将文件从 Azure 文件共享复制到 Azure Blob 的 C# 代码【英文标题】:C# code to Copy Files From Azure File Share to Azure Blob 【发布时间】:2016-05-29 07:39:37 【问题描述】:如何使用 C# 将文件从 Azure 文件共享复制到 Azure Blob?
【问题讨论】:
请告诉我们你到目前为止做了什么以及你面临什么问题。 您使用哪种编程语言? 我正在使用 C# 语言将文件从 Azure 文件共享复制到 Azure Blob。 【参考方案1】:终于搞定了。
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);
【讨论】:
优秀。谢谢!我在 StartCopy 行上不断收到“未找到”错误。你的fileSasUri
解决了这个问题。
@CaseyCrookston,很高兴这个解决方案对你有用。 :)【参考方案2】:
感谢您的帮助,这正是我想要的。更多帮助也可直接通过Microsoft Docs 获得,以处理 blob 上的文件。
这里有更多帮助:
下载 blob 上传 blob 在存储帐户之间复制 BlobCloudBlockBlob destBlob = destContainer.GetBlockBlobReference(sourceBlob.Name); await destBlob.StartCopyAsync(new Uri(GetSharedAccessUri(sourceBlob.Name, sourceContainer))); // Create a SAS token for the source blob, to enable it to be read by the StartCopyAsync method private static string GetSharedAccessUri(string blobName, CloudBlobContainer container) DateTime toDateTime = DateTime.Now.AddMinutes(60); SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = null, SharedAccessExpiryTime = new DateTimeOffset(toDateTime) ; CloudBlockBlob blob = container.GetBlockBlobReference(blobName); string sas = blob.GetSharedAccessSignature(policy); return blob.Uri.AbsoluteUri + sas;
【讨论】:
【参考方案3】: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);
【讨论】:
正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center。 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。以上是关于将文件从 Azure 文件共享复制到 Azure Blob 的 C# 代码的主要内容,如果未能解决你的问题,请参考以下文章