C#连接字符串方式访问微软blob帮助类

Azure Blob 存储

Azure Blob 存储可帮助你创建数据湖以满足分析需求,并提供存储以构建功能强大的云原生和移动应用。通过分层存储你的长期数据优化成本,并且可灵活地纵向扩展高性能计算和机器学习工作负载。

Azure Blob 是唯一一种可为低延迟和交互式方案提供基于 SSD 的高级对象存储层的云存储服务

见官网定义

Nuget 下载 WindowsAzure.Storage包

public class BlobHelper
    {
        private static CloudStorageAccount storageAccount = null;
        private static string filesharebase = "";
        private static CloudBlobClient blobClient = null;
        static BlobHelper()
        {
            string storageConnectionString = ConfigurationManager.AppSettings["storageconnectionstring"];
            if (!CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                throw new Exception("初始化blob fileshare异常");
            }
            blobClient = storageAccount.CreateCloudBlobClient();
            var url = blobClient.BaseUri.ToString();
            if (url.LastIndexOf("/").Equals(url.Length - 1))
            {
                url = url.Substring(0, url.Length - 1);
            }
            filesharebase = url;
        }
        /// <summary>
        /// 上传本地文件到blobfileshare
        /// </summary>
        /// <param name="localPath">本地路径</param>
        /// <param name="toPath">blob路径</param>
        public static void UploadFileToBlob(string localPath, string toPath)
        {
            UploadFile(toPath, localPath: localPath);
        }
        /// <summary>
        /// 上传文件流到blob
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="streamLength"></param>
        /// <param name="toPath"></param>
        public static void UploadStreamToBlob(Stream stream, int streamLength, string toPath)
        {
            UploadFile(toPath, 2, stream: stream, length: streamLength);
        }
        /// <summary>
        /// 上传文件流到blob
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="streamLength"></param>
        /// <param name="toPath"></param>
        public static void UploadByteToBlob(byte[] by, int length, string toPath)
        {
            UploadFile(toPath, 3, by: by, length: length);
        }
        /// <summary>
        /// 上传文件到blob 1物理路径上传 2文件流上传
        /// </summary>
        /// <param name="toPath"></param>
        /// <param name="uploadType"></param>
        /// <param name="localPath">本地物理路径</param>
        public static void UploadFile(string toPath, int uploadType = 1, string localPath = "", Stream stream = null, int length = 0, byte[] by = null)
        {
            var splitArrs = toPath.Split(new string[] { "/", "\\" }, StringSplitOptions.RemoveEmptyEntries);
            CloudBlobContainer container = blobClient.GetContainerReference(splitArrs[0]);
            if (!container.Exists())
            {
                container.CreateAsync();
            }
            var splitLs = splitArrs.ToList();
            splitLs.RemoveAt(0);
            var blobpath = string.Join("/", splitLs.ToArray());
            CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(blobpath);
            if (uploadType == 1)
            {
                if (string.IsNullOrEmpty(localPath))
                {
                    throw new Exception("上传类型为本地文件上传时,物理路径不能为空");
                }
                cloudBlockBlob.UploadFromFile(localPath);
            }
            else if (uploadType == 2)
            {
                if (stream == null || length == 0)
                {
                    throw new Exception("上传类型为流上传时,流和长度不能为空");
                }
                cloudBlockBlob.UploadFromStream(stream, length);
            }
            else if (uploadType == 3)
            {
                if (by == null)
                {
                    throw new Exception("二进制内容不能为空");
                }
                cloudBlockBlob.UploadFromByteArray(by, 0, length);
            }
        }
        /// <summary>
        /// 删除blob的文件
        /// </summary>
        /// <param name="blodPath">blob路径</param>
        public static void DeleteBlodFile(string blodPath)
        {
            var splitArrs = blodPath.Split(new string[] { "/", "\\" }, StringSplitOptions.RemoveEmptyEntries);
            CloudBlobContainer container = blobClient.GetContainerReference(splitArrs[0]);
            if (!container.Exists())
            {
                return;
            }
            var splitLs = splitArrs.ToList();
            splitLs.RemoveAt(0);
            var blobpath = string.Join("/", splitLs.ToArray());
            CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(blobpath);
            if (cloudBlockBlob.Exists())
            {
                cloudBlockBlob.DeleteAsync();
            }
        }

        /// <summary>
        /// 资源url地址
        /// </summary>
        /// <param name="shareFilePath"></param>
        /// <returns></returns>
        public static string GetResourceUrlWithSas(string blobFilePath, string sasToken = "")
        {
            if (string.IsNullOrEmpty(sasToken))
            {
                var splitArrs = blobFilePath.Split(new string[] { "/", "\\" }, StringSplitOptions.RemoveEmptyEntries);
                sasToken = GetAccountSASToken(splitArrs[0]);
            }
            return filesharebase + blobFilePath + sasToken;
        }


        /// <summary>
        /// 资源url地址
        /// </summary>
        /// <param name="shareFilePath"></param>
        /// <returns></returns>
        public static string GetResourceUrl(string blobFilePath)
        {
            return filesharebase + blobFilePath ;
        }

        /// <summary>
        /// 创建sastoken
        /// </summary>
        /// <param name="storageAccount"></param>
        /// <returns></returns>
        public static string GetAccountSASToken(string containerName, int expireMonth = 3)
        {
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);
            SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddMonths(expireMonth),
                Permissions = SharedAccessBlobPermissions.Read
            };
            // Return the SAS token.
            return container.GetSharedAccessSignature(adHocPolicy, null);
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大大黑眼圈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值