微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我们如何使用 C# 更新和上传内容到 Azure 中的 Blob

如何解决我们如何使用 C# 更新和上传内容到 Azure 中的 Blob

我提出问题和答案,希望能让他人受益。你需要安装 Azure.Storage.Blobs 包

解决方法

查看下面的代码

// 一个内容上传类 // 安装包 Azure.Storage.Blobs

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Specialized;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace AnAzureFunctionApp
{
    public class ContentUploader
    {
        public async Task UploadContentsToBlob(string azureStorageAccountConnectionString,string storageContainerName,string blobFileName)
        {
            var blobServiceClient = new BlobServiceClient(azureStorageAccountConnectionString);

            // Create the container and return a container client object
            var containerClient = blobServiceClient.GetBlobContainerClient(storageContainerName);
            await containerClient.CreateIfNotExistsAsync();

            var blobClient = containerClient.GetBlockBlobClient(blobFileName);

            await AddBlobContents(blobClient);
        }

        private async Task AddBlobContents(BlockBlobClient blobClient)
        {
            await using var memoryStream = new MemoryStream();

            // Download the blob's contents if it exist and save it to a memory file
            if (blobClient.Exists())
            {
                var blobDownloadInfo = await blobClient.DownloadAsync();
                await blobDownloadInfo.Value.Content.CopyToAsync(memoryStream);
            }

            byte[] timeBytes = Encoding.UTF8.GetBytes("Process is Run at " + DateTime.Now + Environment.NewLine);
            await memoryStream.WriteAsync(timeBytes,timeBytes.Length);
            memoryStream.Position = 0;

            //Upload the contents
            await blobClient.UploadAsync(memoryStream);
            memoryStream.Close();
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。