栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

C#阿里云OSS——存储

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#阿里云OSS——存储

文章目录
  • 阿里云OSS是什么?
  • 使用步骤
    • 开通OSS和创建AccessKey
  • 项目应用
    • 安装Aliyun.OSS.SDK.NetCore包
    • 编写OSS帮助类,封装SDK提供的方法
    • AliyunOSSHelper.cs 帮助类


阿里云OSS是什么?

OSS是对象存储,简单理解就是一个云盘。可以把文件或者对象存储至OSS,用户下载时走OSS的服务,更快体验更好。

使用步骤 开通OSS和创建AccessKey

开通OSS存储不做过多赘述。以下注重讲一下创建AccessKey

首先先去阿里云RAM访问控制台,点击创建账户


记得勾选编程访问

创建完成后仅显示一次AccessKey的信息,需要妥善保存这些信息

如遇报错
1、Create bucket failed, Put bucket request is not resource owner.创建存储失败,当前账户没有权限。
解决方案:检查RAM控制台改账号有没有管理OSS的权限,如果没有添加一下就可以了。

项目应用 安装Aliyun.OSS.SDK.NetCore包 编写OSS帮助类,封装SDK提供的方法
以下是我根据阿里云官方文档写的一个简易的帮助类,可以在此接触上进行扩展。
AliyunOSSHelper.cs 帮助类

代码运行截图:

阿里云OSS后台截图

using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Org.BouncyCastle.Math.EC.ECCurve;

namespace WanAdmin.Core.Utils
{
    /// 
    /// OSS地域对应的Endpoint
    /// 
    public static class Endpoint
    {
        /// 
        /// 华东1(杭州)
        /// 
        const string HangZhou = "oss-cn-hangzhou.aliyuncs.com";
        /// 
        /// 华东2(上海)
        /// 
        const string ShangHai = "oss-cn-shanghai.aliyuncs.com";
        /// 
        /// 华北1(青岛)
        /// 
        const string QingDao = "oss-cn-qingdao.aliyuncs.com";
        /// 
        /// 华北2(北京)
        /// 
        public const string BeiJing = "oss-cn-beijing.aliyuncs.com";
    }
    public class AliyunOSSHelper
    {
        static string accessKeyId = "你的accessKeyId ";
        static string accessKeySecret = "你的accessKeySecret";
        static string endpoint = Endpoint.BeiJing;

        static OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);


        /// 
        /// 创建存储空间
        /// 
        /// 存储空间名称
        /// 
        public static bool CreateBucket(string bucketName)
        {
            try
            {
                // 创建存储空间。
                var bucket = client.CreateBucket(bucketName);
                Console.WriteLine($"创建存储空间《{bucketName}》成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Create bucket failed, {ex.Message}");
                return false;
            }
            return true;
        }

        /// 
        /// 存储一个字符串
        /// 
        /// 存储空间名称
        /// Key
        /// 字符内容
        /// 
        public static bool PutString(string bucketName, string key, string objectContent)
        {
            try
            {
                byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
                MemoryStream requestContent = new MemoryStream(binaryData);
                // 上传文件。
                client.PutObject(bucketName, key, requestContent);
                Console.WriteLine($"存储字符串《{ objectContent }》成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"存储字符串有误, { ex.Message}");
                return false;
            }
            return true;
        }


        /// 
        /// 上传文件
        /// 
        /// 存储空间名称
        /// 文件路径
        /// Key
        /// 
        public static bool PutObject(string bucketName, string fileToUpload, string key = "")
        {
            if (string.IsNullOrEmpty(key))
            {
                key = Path.GetFileName(fileToUpload);
            }
            try
            {
                // 上传文件。
                var result = client.PutObject(bucketName, key, fileToUpload);
                Console.WriteLine($"上传文件《{ key }》成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"上传文件有误  { ex.Message}");
                return false;
            }
            return true;
        }

        /// 
        /// 文件是否存在
        /// 
        /// 
        /// 
        /// 
        public static bool ExistsObject(string bucketName, string key)
        {
            try
            {
                // 判断文件是否存在。
                var exist = client.DoesObjectExist(bucketName, key);
                Console.WriteLine("Object exist ? " + exist);
                return true;
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. nRequestID:{2}tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
            return false;
        }


        /// 
        /// 删除文件
        /// 
        /// 
        /// 
        /// 
        public static bool DeleteObject(string bucketName, string key)
        {
            try
            {
                // 删除文件。
                client.DeleteObject(bucketName, key);
                Console.WriteLine($"删除文件《{key}》成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除文件有误{ex.Message}");
                return false;
            }
            return true;

        }




        /// 
        /// 获取文件列表
        /// 
        /// 存储空间名称
        /// 
        public static List ListObjects(string bucketName)
        {
            var objectsList = new List();
            try
            {
                ObjectListing result = null;
                string nextMarker = string.Empty;
                do
                {
                    var listObjectsRequest = new ListObjectsRequest(bucketName)
                    {
                        Marker = nextMarker,
                    };
                    // 列举文件。
                    result = client.ListObjects(listObjectsRequest);
                    foreach (var summary in result.ObjectSummaries)
                    {
                        objectsList.Add(summary);
                        Console.WriteLine(summary.Key);
                    }
                    nextMarker = result.NextMarker;
                } while (result.IsTruncated);

            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. nRequestID:{2}tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
            return objectsList;
        }


    }
}

资料文献:
[1]: https://help.aliyun.com/document_detail/32086.html
[2]: https://github.com/aliyun/aliyun-oss-csharp-sdk

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/985170.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号