Exemple #1
0
        public static void CreateBucket(string bucketName)
        {
            var created = false;

            try
            {
                client.CreateBucket(bucketName);
                created = true;
                Console.WriteLine("Created bucket name: " + bucketName);
                client.CreateBucket(bucketName);
            }
            catch (OssException ex)
            {
                if (ex.ErrorCode == OssErrorCode.BucketAlreadyExists)
                {
                    Console.WriteLine("Bucket '{0}' already exists, please modify and recreate it.", bucketName);
                }
                else
                {
                    Console.WriteLine("Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                                      ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                }
            }
            finally
            {
                if (created)
                {
                    client.DeleteBucket(bucketName);
                }
            }
        }
Exemple #2
0
 protected void btnCreateBucket_Click(object sender, EventArgs e)
 {
     OssClient ossClient = new OssClient(endpoint, accessId, accessKey);
     try
     {
         ossClient.CreateBucket(bucketName);
         Console.WriteLine("创建成功!Bucket: " + bucketName);
     }
     catch (OssException ex)
     {
         if (ex.ErrorCode == OssErrorCode.BucketAlreadyExists)
         {
             // 这里示例处理一种特定的ErrorCode。
             Console.WriteLine(string.Format("Bucket '{0}' 已经存在,请更改名称后再创建。", bucketName));
         }
         else
         {
             // RequestID和HostID可以在有问题时用于联系客服诊断异常。
             Console.WriteLine(string.Format("创建失败。错误代码:{0}; 错误消息:{1}。\nRequestID:{2}\tHostID:{3}",
                 ex.ErrorCode,
                 ex.Message,
                 ex.RequestId,
                 ex.HostId));
         }
     }
 }
Exemple #3
0
 public async Task SaveBlobStreamAsync(string containerName, string blobName, Stream source, BlobProperties properties = null)
 {
     try
     {
         await Task.Run(() =>
         {
             var exist = _ossClient.DoesBucketExist(containerName);
             if (!exist)
             {
                 _ossClient.CreateBucket(containerName);
             }
             var md5        = OssUtils.ComputeContentMd5(source, source.Length);
             var objectMeta = new ObjectMetadata();
             objectMeta.AddHeader("Content-MD5", md5);
             objectMeta.UserMetadata.Add("Content-MD5", md5);
             if (properties != null)
             {
                 objectMeta.ContentType = properties.ContentType;
             }
             _ossClient.PutObject(containerName, blobName, source, objectMeta);
         });
     }
     catch (Exception ex)
     {
         if (ex.IsOssStorageException())
         {
             throw ex.Convert();
         }
         throw;
     }
 }
        public void CreateBucketWithColdArchiveStorageClassTest()
        {
            var client = new OssClient("http://oss-ap-southeast-2.aliyuncs.com", Config.AccessKeyId, Config.AccessKeySecret);

            //get a random bucketName
            var bucketName = OssTestUtils.GetBucketName(_className);

            //assert bucket does not exist
            Assert.IsFalse(OssTestUtils.BucketExists(client, bucketName),
                           string.Format("Bucket {0} should not exist before creation", bucketName));

            //create a new bucket
            var request = new CreateBucketRequest(bucketName, StorageClass.ColdArchive, CannedAccessControlList.PublicReadWrite);

            client.CreateBucket(request);
            OssTestUtils.WaitForCacheExpire();
            Assert.IsTrue(OssTestUtils.BucketExists(client, bucketName),
                          string.Format("Bucket {0} should exist after creation", bucketName));

            //delete the new created bucket
            client.DeleteBucket(bucketName);
            OssTestUtils.WaitForCacheExpire();
            Assert.IsFalse(OssTestUtils.BucketExists(client, bucketName),
                           string.Format("Bucket {0} should not exist after deletion", bucketName));
        }
Exemple #5
0
        public FileOssClient(FileOssConfig config)
        {
            string endpoint        = config.Endpoint;
            string accessKeyId     = config.AccessKeyId;
            string accessKeySecret = config.AccessKeySecret;

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

            bucketName = config.BucketName;

            try
            {
                bool isCreateBucket = true;
                foreach (Bucket bucket in client.ListBuckets())
                {
                    if (bucket != null && bucketName.Equals(bucket.Name))
                    {
                        isCreateBucket = false;
                        break;
                    }
                }
                //if (client.ListBuckets().Where(p => p.Equals(bucketName)).First() == null)
                if (isCreateBucket)
                {
                    client.CreateBucket(bucketName);
                }
            } catch (Exception ex)
            {
                Console.WriteLine("exMsg:" + ex.Message);
            }
        }
Exemple #6
0
        public Task <bool> CreateBucketAsync(string bucketName)
        {
            if (string.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException(nameof(bucketName));
            }
            //检查桶是否存在
            Bucket bucket = ListBucketsAsync().Result?.Where(p => p.Name == bucketName)?.FirstOrDefault();

            if (bucket != null)
            {
                string localtion = Options.Endpoint?.Split('.')[0];
                if (bucket.Location.Equals(localtion, StringComparison.OrdinalIgnoreCase))
                {
                    throw new BucketExistException($"Bucket '{bucketName}' already exists.");
                }
                else
                {
                    throw new BucketExistException($"There have a same name bucket '{bucketName}' in other localtion '{bucket.Location}'.");
                }
            }
            var request = new CreateBucketRequest(bucketName)
            {
                //设置存储空间访问权限ACL。
                ACL = CannedAccessControlList.Private,
                //设置数据容灾类型。
                DataRedundancyType = DataRedundancyType.LRS
            };
            // 创建存储空间。
            var result = _client.CreateBucket(request);

            return(Task.FromResult(result != null));
        }
        public async Task createBucket(string bucketName, CannedAccessControlList accessControl)
        {
            Bucket bucket = await _ossClient.CreateBucket(bucketName);

            await _ossClient.SetBucketAcl(bucketName, accessControl);

            this.Add(bucket);
        }
Exemple #8
0
 /// <summary>
 /// 创建新的Bucket
 /// </summary>
 /// <param name="bucketName">oss磁盘名称</param>
 public void CreateBucket(string bucketName)
 {
     ////初始化 OSSClient
     //OssClient ossClient = new OssClient(endPoint, accessKeyId, accessKeySecret);
     // 新建一个Bucket
     client.CreateBucket(bucketName);
     // 设置bucket权限
     client.SetBucketAcl(bucketName, CannedAccessControlList.PublicRead);
 }
Exemple #9
0
 public Task Init()
 {
     Client = new OssClient(EndPoint, AccessKeyId, AccessKeySecret);
     if (!Client.DoesBucketExist(DefaultBucket))
     {
         Client.CreateBucket(DefaultBucket);
     }
     return(Task.CompletedTask);
 }
Exemple #10
0
        public static void CreateEmptyFolder()
        {
            const string accessKeyId     = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint        = "<valid endpoint>";

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

            const string bucketName = "<your bucket>";
            // Note: key treats as a folder and must end with slash.
            const string key      = "yourfolder/";
            var          created  = false;
            var          uploaded = false;

            try
            {
                // create bucket
                client.CreateBucket(bucketName);
                created = true;
                Console.WriteLine("Created bucket name: " + bucketName);

                // put object with zero bytes stream.
                using (MemoryStream memStream = new MemoryStream())
                {
                    PutObjectResult ret = client.PutObject(bucketName, key, memStream);
                    uploaded = true;
                    Console.WriteLine("Uploaded empty object's ETag: " + ret.ETag);
                }
            }
            catch (OssException ex)
            {
                if (ex.ErrorCode == OssErrorCode.BucketAlreadyExists)
                {
                    Console.WriteLine("Bucket '{0}' already exists, please modify and recreate it.", bucketName);
                }
                else
                {
                    Console.WriteLine("CreateBucket Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                                      ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                }
            }
            finally
            {
                if (uploaded)
                {
                    client.DeleteObject(bucketName, key);
                }
                if (created)
                {
                    client.DeleteBucket(bucketName);
                }
            }
        }
Exemple #11
0
 /// <summary>
 /// 创建一个新的存储空间
 /// </summary>
 private static void CreateBucket()
 {
     try
     {
         var result = _client.CreateBucket(_bucketName);
         Console.WriteLine("创建存储空间{0}成功", result.Name);
     }
     catch (Exception ex)
     {
         Console.WriteLine("创建存储空间失败. 原因:{0}", ex.Message);
     }
 }
        public static void CreateEmptyFolder()
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid endpoint>";

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

            const string bucketName = "<your bucket>";
            // Note: key treats as a folder and must end with slash.
            const string key = "yourfolder/";
            var created = false;
            var uploaded = false;
            try
            {
                // create bucket
                client.CreateBucket(bucketName);
                created = true;
                Console.WriteLine("Created bucket name: " + bucketName);

                // put object with zero bytes stream.
                using (MemoryStream memStream = new MemoryStream())
                {
                    PutObjectResult ret = client.PutObject(bucketName, key, memStream);
                    uploaded = true;
                    Console.WriteLine("Uploaded empty object's ETag: " + ret.ETag);
                }
            }
            catch (OssException ex)
            {
                if (ex.ErrorCode == OssErrorCode.BucketAlreadyExists)
                {
                    Console.WriteLine("Bucket '{0}' already exists, please modify and recreate it.", bucketName);
                }
                else
                {
                    Console.WriteLine("CreateBucket Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                }
            }
            finally
            {
                if (uploaded)
                {
                    client.DeleteObject(bucketName, key);
                }
                if (created)
                {
                    client.DeleteBucket(bucketName);
                }
            }
        }
Exemple #13
0
 public void CreateBucket(string bucketName, Acl acl)
 {
     try
     {
         var client = new OssClient(_endPoint, _accessKeyId, _accessKeySecret);
         client.CreateBucket(bucketName);
         client.SetBucketAcl(bucketName, (CannedAccessControlList)acl);
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
Exemple #14
0
        public static bool CreateBucket(OssClient client, string bucketName)
        {
            TkDebug.AssertArgumentNull(client, "client", null);
            TkDebug.AssertArgumentNullOrEmpty(bucketName, "bucketName", null);

            bucketName = bucketName.ToLower(ObjectUtil.SysCulture);
            if (!client.DoesBucketExist(bucketName))
            {
                client.CreateBucket(bucketName);
                return(true);
            }
            return(false);
        }
 /// <summary>
 /// CreateBucket
 /// </summary>
 /// <param name="bucketName">BucketName</param>
 /// <returns>result</returns>
 public bool CreateBucket()
 {
     try
     {
         var bucket = client.CreateBucket(bucketName);
         return(true);
     }
     catch (OssException ex)
     {
         lastError = ex;
         return(false);
     }
 }
        /// <summary>
        /// 创建一个新的存储空间(Bucket)
        /// </summary>
        /// <param name="bucketName">存储空间的名称</param>
        public static void CreateBucket(string bucketName)
        {
            try
            {
                client.CreateBucket(bucketName);

                Console.WriteLine("Created bucket name:{0} succeeded ", bucketName);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                                  ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
        }
        public static void CreateBucket(string bucketName)
        {
            const string accessKeyId     = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint        = "<valid host name>";

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

            var created = false;

            try
            {
                client.CreateBucket(bucketName);
                created = true;
                Console.WriteLine("Created bucket name: " + bucketName);
                client.CreateBucket(bucketName);
            }
            catch (OssException ex)
            {
                if (ex.ErrorCode == OssErrorCode.BucketAlreadyExists)
                {
                    Console.WriteLine("Bucket '{0}' already exists, please modify and recreate it.", bucketName);
                }
                else
                {
                    Console.WriteLine("Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                                      ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                }
            }
            finally
            {
                if (created)
                {
                    client.DeleteBucket(bucketName);
                }
            }
        }
Exemple #18
0
        /// <summary>
        /// 在OSS中创建一个新的存储空间。
        /// </summary>
        /// <param name="bucketName">要创建的存储空间的名称</param>
        public static void CreateBucket(string bucketName)
        {
            var client = new OssClient(Tools.AliYunTools._ossEndpointURL, OSSACCESSKEYID, ACCESSKEYSECRET);

            try
            {
                client.CreateBucket(bucketName);
                client.SetBucketAcl(bucketName, CannedAccessControlList.PublicRead);//设置权限为公共读写
            }
            catch (Exception ex)
            {
                // LogText();
                throw new Exception(string.Format("Create bucket failed, {0}", ex.Message));
            }
        }
 /// <summary>
 /// 创建 Bucket 容器,权限默认为公开读 ,如果成功则返回 bucket ,失败则 throw 异常。
 /// </summary>
 /// <param name="bucketName"></param>
 /// <returns></returns>
 public static Bucket CreateBucket(string bucketName)
 {
     try
     {
         // 创建容器
         Bucket bucket = client.CreateBucket(bucketName);
         // 设置容器权限 公共读,任何人都可以读,有权限才可以写
         client.SetBucketAcl(bucketName, CannedAccessControlList.PublicRead);
         return(bucket);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public static void CreateBucket(string bucketName)
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid host name>";

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

            var created = false;
            try
            {
                client.CreateBucket(bucketName);
                created = true;
                Console.WriteLine("Created bucket name: " + bucketName);
                client.CreateBucket(bucketName);
            }
            catch (OssException ex)
            {
                if (ex.ErrorCode == OssErrorCode.BucketAlreadyExists)
                {
                    Console.WriteLine("Bucket '{0}' already exists, please modify and recreate it.", bucketName);
                }
                else
                {
                    Console.WriteLine("Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                }
            }
            finally
            {
                if (created)
                {
                    client.DeleteBucket(bucketName);
                }
            }
        }
Exemple #21
0
        /// <summary>
        /// 创建一个新的存储空间(Bucket)
        /// </summary>
        /// <param name="bucketName">存储空间的名称</param>
        public static bool CreateBucket(string bucketName)
        {
            bool success = false;

            try
            {
                // 新建一个Bucket
                ossClient.CreateBucket(bucketName);
                success = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create bucket failed. {0}", ex.Message);
            }
            return(success);
        }
Exemple #22
0
        private void button1_Click(object sender, EventArgs e)
        {
            // 创建OSSClient实例。
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                // 创建存储空间。
                var bucket = client.CreateBucket(bucketName);

                show_log("Create bucket succeeded  ");
            }
            catch (Exception)
            {
                show_log("Create bucket false  ");
            }
        }
        public AliyunFileStorage(AliyunFileStorageOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var connectionString = new AliyunFileStorageConnectionStringBuilder(options.ConnectionString);

            _client     = new OssClient(connectionString.Endpoint, connectionString.AccessKey, connectionString.SecretKey);
            _bucket     = connectionString.Bucket;
            _serializer = options.Serializer ?? DefaultSerializer.Instance;
            if (!DoesBucketExist(_bucket))
            {
                _client.CreateBucket(_bucket);
            }
        }
        //初始化OssClient并创造存储空间
        public void CreatBucket(string bucketName)
        {
            ////其他参数
            //ClientConfiguration conf = new ClientConfiguration();
            //conf.MaxErrorRetry = 3;
            //conf.ConnectionTimeout = 300;
            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                var bucket = client.CreateBucket("igetsss");
                Console.Write("成功创建");
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
        public async Task <bool> CreateBucketAsync(string bucketName)
        {
            if (string.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException(nameof(bucketName));
            }
            var request = new CreateBucketRequest(bucketName)
            {
                //设置存储空间访问权限ACL。
                ACL = CannedAccessControlList.Private,
                //设置数据容灾类型。
                DataRedundancyType = DataRedundancyType.ZRS
            };
            // 创建存储空间。
            var result = _client.CreateBucket(request);

            return(await Task.FromResult(result != null));
        }
Exemple #26
0
 private static OssClient CreateOssClientOfIOS()
 {
     if (_ossClient == null)
     {
         string accessKeyId     = "3JkljJxvXgjLz80X";
         string accessKeySecret = "L2ERHORPk3WkjqfGUb27RlxvT8x5f3";
         string endpoint        = "oss-cn-beijing.aliyuncs.com";
         //var conf = new ClientConfiguration();
         ////conf.IsCname = true;/// 配置使用Cname
         ////conf.ConnectionLimit = 512;  //HttpWebRequest最大的并发连接数目
         //conf.MaxErrorRetry = 3;     //设置请求发生错误时最大的重试次数
         //conf.ConnectionTimeout = 300;  //设置连接超时时间
         ////conf.SetCustomEpochTicks(customEpochTicks);        //设置自定义基准时间, CreateCancelTokenSource().Token.ToString()
         _ossClient = new OssClient(endpoint, accessKeyId, accessKeySecret);
         var exist = _ossClient.DoesBucketExist("vgic");
         if (!exist)
         {
             _ossClient.CreateBucket("vgic");
         }
     }
     return(_ossClient);
 }
        public bool CreateBucket(string bucketName, ref string msg)
        {
            try
            {
                _ossClient.CreateBucket(bucketName);

                return(true);
            }
            catch (OssException ex)
            {
                msg = ex.Message;
                _logger.LogError("Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                                 ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                _logger.LogError("Failed with error info: {0}", ex.Message);
            }

            return(false);
        }
Exemple #28
0
        //从config获取云端设置
        public bool setUpConnect()
        {
            // 创建OSSClient实例。
            this.client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            try
            {
                updateCloudFileList();
                if (!this.client.DoesBucketExist(this.bucketName))
                {
                    // 创建存储空间。
                    this.bucket = client.CreateBucket(bucketName);
                    System.Console.WriteLine("Create bucket succeeded, {0} ", bucket.Name);
                }
                return(true);
            }
            catch (System.Exception ex)
            {
                return(false);

                System.Console.WriteLine(ex.Message);
            }
        }
        public void CreateAndDeleteBucketDefaultRegionTest()
        {
            var settings = AccountSettings.Load();
            //point to default region
            var ossClient = new OssClient(settings.OssEndpoint, settings.OssAccessKeyId, settings.OssAccessKeySecret);

            //get a random bucketName
            var bucketName = OssTestUtils.GetBucketName(_className);

            //assert bucket does not exist
            Assert.IsFalse(OssTestUtils.BucketExists(ossClient, bucketName),
                string.Format("Bucket {0} should not exist before creation", bucketName));

            //create a new bucket
            ossClient.CreateBucket(bucketName);
            Assert.IsTrue(ossClient.DoesBucketExist(bucketName),
                string.Format("Bucket {0} should exist after creation", bucketName));

            //delete the bucket
            ossClient.DeleteBucket(bucketName);
            Assert.IsFalse(ossClient.DoesBucketExist(bucketName),
                string.Format("Bucket {0} should not exist after deletion", bucketName));
        }
        public void CreateAndDeleteBucketDefaultRegionTest()
        {
            var settings = AccountSettings.Load();
            //point to default region
            var ossClient = new OssClient(settings.OssEndpoint, settings.OssAccessKeyId, settings.OssAccessKeySecret);

            //get a random bucketName
            var bucketName = OssTestUtils.GetBucketName(_className);

            //assert bucket does not exist
            Assert.IsFalse(OssTestUtils.BucketExists(ossClient, bucketName),
                           string.Format("Bucket {0} should not exist before creation", bucketName));

            //create a new bucket
            ossClient.CreateBucket(bucketName);
            Assert.IsTrue(ossClient.DoesBucketExist(bucketName),
                          string.Format("Bucket {0} should exist after creation", bucketName));

            //delete the bucket
            ossClient.DeleteBucket(bucketName);
            Assert.IsFalse(ossClient.DoesBucketExist(bucketName),
                           string.Format("Bucket {0} should not exist after deletion", bucketName));
        }
Exemple #31
0
        /// <summary>
        /// 创建bucket
        /// </summary>
        /// <param name="bucketName">bucket名</param>
        /// <param name="aclType">开放类型</param>
        /// <param name="ossPoint">站点</param>
        /// <param name="accessId">accessId</param>
        /// <param name="accessKey">accessKey</param>
        /// <returns></returns>
        public static bool CreateBucket(string bucketName, string aclType)
        {
            if (string.IsNullOrWhiteSpace(bucketName))
            {
                throw new Exception("Bucket名称为空");
            }



            //建立Oss客户端连接
            OssClient client = ConnOssClient();

            if (client.DoesBucketExist(bucketName))
            {
                throw new Exception("Bucket已经存在");
            }

            //创建Bucket
            client.CreateBucket(bucketName);

            //设置读写
            switch (aclType)
            {
            case "1":
                client.SetBucketAcl(bucketName, CannedAccessControlList.PublicRead);
                break;

            case "2":
                client.SetBucketAcl(bucketName, CannedAccessControlList.Private);
                break;

            default:
                client.SetBucketAcl(bucketName, CannedAccessControlList.PublicReadWrite);
                break;
            }
            return(true);
        }
 /// <summary>
 ///     保存对象到指定的容器
 /// </summary>
 /// <param name="containerName"></param>
 /// <param name="blobName"></param>
 /// <param name="source"></param>
 public async Task SaveBlobStream(string containerName, string blobName, Stream source)
 {
     try
     {
         await Task.Run(() =>
         {
             var exist = _ossClient.DoesBucketExist(containerName);
             if (!exist)
             {
                 _ossClient.CreateBucket(containerName);
             }
             var md5        = OssUtils.ComputeContentMd5(source, source.Length);
             var objectMeta = new ObjectMetadata();
             objectMeta.AddHeader("Content-MD5", md5);
             objectMeta.UserMetadata.Add("Content-MD5", md5);
             _ossClient.PutObject(containerName, blobName, source, objectMeta);
         });
     }
     catch (Exception ex)
     {
         throw new StorageException(StorageErrorCode.PostError.ToStorageError(),
                                    new Exception(ex.ToString()));
     }
 }
 public void CreateBucket(string bucketName)
 {
     ossClient.CreateBucket(bucketName);
 }
Exemple #34
0
 public void CreateBuckey()
 {
     client.CreateBucket("jingge2016");
 }