Beispiel #1
0
 /// 获取对象列表与子目录
 public void GetBucketWithDelimiter()
 {
     //.cssg-snippet-body-start:[get-bucket-with-delimiter]
     try
     {
         string           bucket  = "examplebucket-1250000000"; //格式:BucketName-APPID
         GetBucketRequest request = new GetBucketRequest(bucket);
         //获取 a/ 下的对象以及子目录
         request.SetPrefix("a/");
         //执行请求
         GetBucketResult result = cosXml.GetBucket(request);
         //bucket的相关信息
         ListBucket info = result.listBucket;
         // 对象列表
         List <ListBucket.Contents> objects = info.contentsList;
         // 子目录列表
         List <ListBucket.CommonPrefixes> subDirs = info.commonPrefixesList;
     }
     catch (COSXML.CosException.CosClientException clientEx)
     {
         //请求失败
         Console.WriteLine("CosClientException: " + clientEx);
     }
     catch (COSXML.CosException.CosServerException serverEx)
     {
         //请求失败
         Console.WriteLine("CosServerException: " + serverEx.GetInfo());
     }
     //.cssg-snippet-body-end
 }
Beispiel #2
0
        /// <summary>
        ///     列出指定容器下的对象列表
        /// </summary>
        /// <param name="containerName"></param>
        /// <returns></returns>
        public async Task <IList <BlobFileInfo> > ListBlobs(string containerName)
        {
            if (!string.IsNullOrWhiteSpace(containerName) && !containerName.EndsWith("/"))
            {
                containerName += "/";
            }

            var req = new GetBucketRequest(_tcConfig.BucketName);

            req.SetPrefix(containerName);
            var resp = _cosXmlServer.GetBucket(req);
            await resp.HandlerError("获取对象列表出错!");

            var list = resp.listBucket.contentsList
                       .Select(obj =>
                               new BlobFileInfo
            {
                Container    = containerName?.Trim('/'),
                ETag         = obj.eTag,
                Length       = obj.size,
                LastModified = Convert.ToDateTime(obj.lastModified),
                Name         = obj.key.Replace(containerName, string.Empty),
                Url          = GetUrlByKey(obj.key),
                //ContentMD5 =
            });

            return(list.ToArray());
        }
Beispiel #3
0
        /// <summary>
        /// 查询指定路径下面的对象
        /// </summary>
        /// <param name="tEST"></param>
        /// <returns></returns>
        public ResultModel <ListBucket> GetBucketResult(string tEST)
        {
            CosXmlConfig config = new CosXmlConfig.Builder()
                                  .SetConnectionTimeoutMs(SetConnectionTimeoutMs) //设置连接超时时间,单位毫秒,默认45000ms
                                  .SetReadWriteTimeoutMs(SetReadWriteTimeoutMs)   //设置读写超时时间,单位毫秒,默认45000ms
                                  .IsHttps(IsHttps)                               //设置默认 HTTPS 请求
                                  .SetAppid(SetAppid)                             //设置腾讯云账户的账户标识 APPID
                                  .SetRegion(SetRegion)                           //设置一个默认的存储桶地域
                                  .Build();
            string secretId       = SecretId;                                     //云 API 密钥 SecretId
            string secretKey      = SecretKey;                                    //云 API 密钥 SecretKey
            long   durationSecond = 600;                                          //每次请求签名有效时长,单位为秒
            QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId,
                                                                                                    secretKey, durationSecond);

            CosXml cosXml = new CosXmlServer(config, qCloudCredentialProvider);
            ResultModel <ListBucket> resu = new ResultModel <ListBucket>();

            try
            {
                string           bucket  = "yuanguhl"; //格式:BucketName-APPID
                GetBucketRequest request = new GetBucketRequest(bucket);
                request.Region = "ap-beijing";
                //设置签名有效时长
                request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
                //获取 a/ 下的对象
                if (!string.IsNullOrEmpty(tEST))
                {
                    request.SetPrefix(tEST);
                }
                //执行请求
                GetBucketResult result = cosXml.GetBucket(request);
                //请求成功
                resu.date    = result.listBucket;
                resu.success = true;
                return(resu);
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                resu.success = false;
                resu.message = clientEx.InnerException.ToString();
                return(resu);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                resu.success = false;
                resu.message = serverEx.InnerException.ToString();
                return(resu);
            }
        }
        /// 指定前缀批量删除对象
        public void DeletePrefix()
        {
            //.cssg-snippet-body-start:[delete-prefix]
            try
            {
                String nextMarker = null;

                // 循环请求直到没有下一页数据
                do
                {
                    string           bucket      = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID
                    string           prefix      = "folder1/";                 //指定前缀
                    GetBucketRequest listRequest = new GetBucketRequest(bucket);
                    //获取 folder1/ 下的所有对象以及子目录
                    listRequest.SetPrefix(prefix);
                    listRequest.SetMarker(nextMarker);
                    //执行列出对象请求
                    GetBucketResult listResult = cosXml.GetBucket(listRequest);
                    ListBucket      info       = listResult.listBucket;
                    // 对象列表
                    List <ListBucket.Contents> objects = info.contentsList;
                    // 下一页的下标
                    nextMarker = info.nextMarker;

                    DeleteMultiObjectRequest deleteRequest = new DeleteMultiObjectRequest(bucket);
                    //设置返回结果形式
                    deleteRequest.SetDeleteQuiet(false);
                    //对象列表
                    List <string> deleteObjects = new List <string>();
                    foreach (var content in objects)
                    {
                        deleteObjects.Add(content.key);
                    }
                    deleteRequest.SetObjectKeys(deleteObjects);
                    //执行批量删除请求
                    DeleteMultiObjectResult deleteResult = cosXml.DeleteMultiObjects(deleteRequest);
                    //打印请求结果
                    Console.WriteLine(deleteResult.GetResultInfo());
                } while (nextMarker != null);
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }
            //.cssg-snippet-body-end
        }
Beispiel #5
0
        public IEnumerable <IFileEntry> List()
        {
            bool   isTruncated = true;
            string filename    = null;

            while (isTruncated)
            {
                cosXml = GetCosXml();
                string bucket = _cosOptions.Bucket;
                string prefix = _cosOptions.Path;

                GetBucketRequest request = new GetBucketRequest(bucket);

                request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);

                if (!string.IsNullOrEmpty(filename))
                {
                    request.SetMarker(filename);
                }

                if (!string.IsNullOrEmpty(prefix))
                {
                    request.SetPrefix(prefix);
                }

                GetBucketResult result = cosXml.GetBucket(request);

                ListBucket info = result.listBucket;

                isTruncated = result.listBucket.isTruncated;
                filename    = result.listBucket.nextMarker;

                foreach (var item in info.contentsList)
                {
                    var last = DateTime.Parse(item.lastModified);

                    var fileName = item.key;
                    if (!string.IsNullOrWhiteSpace(prefix))
                    {
                        fileName = fileName.Substring(prefix.Length);

                        if (fileName.StartsWith("/", StringComparison.Ordinal))
                        {
                            fileName = fileName.Trim('/');
                        }
                    }

                    yield return(new FileEntry(fileName, item.size, last, last));
                }
            }
        }
        public async Task <List <Item> > ListObjectsAsync(string bucketName, string prefix = null)
        {
            if (string.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException(nameof(bucketName));
            }
            bucketName = ConvertBucketName(bucketName);
            ListBucket  info       = null;
            string      nextMarker = null;
            List <Item> items      = new List <Item>();

            do
            {
                GetBucketRequest request = new GetBucketRequest(bucketName);
                if (!string.IsNullOrEmpty(nextMarker))
                {
                    request.SetMarker(nextMarker);
                }
                if (!string.IsNullOrEmpty(prefix))
                {
                    request.SetPrefix(prefix);
                }
                //执行请求
                GetBucketResult result = _client.GetBucket(request);
                //bucket的相关信息
                info = result.listBucket;
                if (info.isTruncated)
                {
                    // 数据被截断,记录下数据下标
                    nextMarker = info.nextMarker;
                }
                foreach (var item in info.contentsList)
                {
                    items.Add(new Item()
                    {
                        Key          = item.key,
                        LastModified = item.lastModified,
                        ETag         = item.eTag,
                        Size         = (ulong)item.size,
                        IsDir        = false,
                        BucketName   = bucketName,
                        VersionId    = null,
                    });
                }
            } while (info.isTruncated);
            return(await Task.FromResult(items));
        }
Beispiel #7
0
        public void getBucket()
        {
            //.cssg-snippet-body-start:[get-bucket]
            CosXmlConfig config = new CosXmlConfig.Builder()
                                  .SetConnectionTimeoutMs(60000) //设置连接超时时间,单位毫秒,默认45000ms
                                  .SetReadWriteTimeoutMs(40000)  //设置读写超时时间,单位毫秒,默认45000ms
                                  .IsHttps(true)                 //设置默认 HTTPS 请求
                                  .SetAppid("1253653367")        //设置腾讯云账户的账户标识 APPID
                                  .SetRegion("ap-guangzhou")     //设置一个默认的存储桶地域
                                  .Build();

            string secretId       = Environment.GetEnvironmentVariable("COS_KEY");    //云 API 密钥 SecretId
            string secretKey      = Environment.GetEnvironmentVariable("COS_SECRET"); //云 API 密钥 SecretKey
            long   durationSecond = 600;                                              //每次请求签名有效时长,单位为秒
            QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId,
                                                                                                    secretKey, durationSecond);

            CosXml cosXml = new CosXmlServer(config, qCloudCredentialProvider);

            try
            {
                string           bucket  = "bucket-cssg-test-dotnet-1253653367"; //格式:BucketName-APPID
                GetBucketRequest request = new GetBucketRequest(bucket);
                //设置签名有效时长
                request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
                //获取 a/ 下的对象
                request.SetPrefix("a/");
                //执行请求
                GetBucketResult result = cosXml.GetBucket(request);
                //bucket的相关信息
                ListBucket info = result.listBucket;
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
                Assert.Null(clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
                Assert.Null(serverEx);
            }
            //.cssg-snippet-body-end
        }
Beispiel #8
0
        public static void AsynGetBucket(COSXML.CosXml cosXml, string bucket)
        {
            GetBucketRequest request = new GetBucketRequest(bucket);

            request.SetPrefix("a/bed/d");
            List <string> queryParameters = new List <string>();

            queryParameters.Add("prefix");
            queryParameters.Add("max-keys");
            //设置签名有效时长
            request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600, null, queryParameters);
            ////设置签名有效时长
            //request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);


            ///执行请求
            cosXml.GetBucket(request,
                             delegate(CosResult cosResult)
            {
                GetBucketResult result = cosResult as GetBucketResult;
                Console.WriteLine(result.GetResultInfo());
            },
                             delegate(CosClientException clientEx, CosServerException serverEx)
            {
                if (clientEx != null)
                {
                    QLog.D("XIAO", clientEx.Message);
                    Console.WriteLine("CosClientException: " + clientEx.Message);
                }
                if (serverEx != null)
                {
                    QLog.D("XIAO", serverEx.Message);
                    Console.WriteLine("CosServerException: " + serverEx.GetInfo());
                }
            });
        }
Beispiel #9
0
        public static void GetBucket(COSXML.CosXml cosXml, string bucket)
        {
            GetBucketRequest request = new GetBucketRequest(bucket);

            //设置签名有效时长
            //request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);

            request.SetPrefix("a/中文/d");

            List <string> headerKeys = new List <string>();

            headerKeys.Add("Host");


            List <string> queryParameters = new List <string>();

            queryParameters.Add("prefix");
            queryParameters.Add("max-keys");

            request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600, headerKeys, queryParameters);


            //执行请求
            GetBucketResult result = cosXml.GetBucket(request);

            Console.WriteLine(result.GetResultInfo());

            //try
            //{
            //    GetBucketRequest request = new GetBucketRequest(bucket);

            //    //设置签名有效时长
            //    //request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);

            //    request.SetPrefix("a/中文/d");

            //    List<string> headerKeys = new List<string>();
            //    headerKeys.Add("Host");


            //    List<string> queryParameters = new List<string>();
            //    queryParameters.Add("prefix");
            //    queryParameters.Add("max-keys");

            //    request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600, headerKeys, queryParameters);


            //    //执行请求
            //    GetBucketResult result = cosXml.GetBucket(request);
            //    Console.WriteLine(result.GetResultInfo());
            //}
            //catch (COSXML.CosException.CosClientException clientEx)
            //{
            //    QLog.D("XIAO", clientEx.Message);
            //    Console.WriteLine("CosClientException: " + clientEx.Message);
            //}
            //catch (COSXML.CosException.CosServerException serverEx)
            //{
            //    QLog.D("XIAO", serverEx.Message);
            //    Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            //}
        }
Beispiel #10
0
        /// <summary>
        /// 查找新版本更新文件路径
        /// </summary>
        /// <returns></returns>
        public Task <(string path, string version)> FindNewUpdate()
        {
            CoreEngine.Current.Logger.Info($"检查更新:查找新版本");
            var tcsResult = new TaskCompletionSource <(string s, string ss)>();

            if (null == SuperEngine.Current.GlobalConfig)
            {
                CoreEngine.Current.Logger.Info($"检查更新失败:更新配置为空");
                tcsResult.SetResult((null, null));
                return(tcsResult.Task);
            }
            string fileHeadPath = $@"https://{SuperEngine.Current.GlobalConfig.BucketName}.cos.{SuperEngine.Current.GlobalConfig.Region}.myqcloud.com/";

            CoreEngine.Current.Logger.Info($"检查更新:版本更新文件路径:{fileHeadPath}");
            try
            {
                string           bucket  = SuperEngine.Current.GlobalConfig.BucketName; //格式:BucketName-APPID
                GetBucketRequest request = new GetBucketRequest(bucket);
                //设置签名有效时长
                request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
                //获取 a/ 下的对象
                request.SetPrefix(SuperEngine.Current.GlobalConfig.UpdatePath);
                if (null == SuperEngine.Current.CosXml)
                {
                    tcsResult.SetResult((null, null));
                    return(tcsResult.Task);
                }
                request.SetMaxKeys("10");
                CoreEngine.Current.Logger.Info($"检查更新:请求网络");
                //执行请求
                GetBucketResult result = SuperEngine.Current.CosXml.GetBucket(request);
                //请求成功
                var entityList = result.listBucket.contentsList;
                CoreEngine.Current.Logger.Info($"检查更新:请求成功,返回条目数量:{entityList.Count}");
                var list = entityList.OrderByDescending(a => a.lastModified).ToList();
                foreach (var ett in list)
                {
                    var fullPath  = Path.Combine(fileHeadPath, ett.key);
                    var extension = Path.GetExtension(fullPath);
                    if (extension == ".bwp")
                    {
                        var fileName = Path.GetFileNameWithoutExtension(fullPath);
                        try
                        {
                            if (SuperEngine.Current.IsVersionNewer(fileName))
                            {
                                //return fullPath;
                                tcsResult.SetResult((fullPath, fileName));
                                return(tcsResult.Task);
                            }
                        }
                        catch
                        {
                            break;
                        }
                    }
                }
                tcsResult.SetResult((null, null));
                return(tcsResult.Task);
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                CoreEngine.Current.Logger.Error(clientEx, $"检查更新失败:COS客户端异常");
                Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                CoreEngine.Current.Logger.Error(serverEx, $"检查更新失败:COS服务端异常");
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }
            catch (Exception e)
            {
                CoreEngine.Current.Logger.Error(e, $"检查更新失败:其他异常");
            }
            tcsResult.SetResult((null, null));
            return(tcsResult.Task);
        }