private void tsbConnect_Click(object sender, EventArgs e) { string id = teaccessId.Text.Trim(); string key = teaccesskey.Text.Trim(); if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(key)) { MessageBox.Show("Access id 或 acess key 不能为空。", ""); return; } ossConfig.AccessId = id; ossConfig.AccessKey = key; setConnEnaled(false); ThreadPool.QueueUserWorkItem(o => { try { ossClient = new OssClient(id, key); IEnumerable <Bucket> buck = ossClient.ListBuckets(); setTexItems("连接成功。"); setEnaled(true); setConnEnaled(true); setItems(buck); SetMemory(); } catch (Exception ex) { setTexItems("连接失败。\r\n 失败原因:" + ex.Message); setEnaled(false); setConnEnaled(true); } }); }
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); } }
public Task <List <Bucket> > ListBucketsAsync() { IEnumerable <Aliyun.OSS.Bucket> buckets = _client.ListBuckets(); if (buckets == null) { return(null); } if (buckets.Count() == 0) { return(Task.FromResult(new List <Bucket>())); } var resultList = new List <Bucket>(); foreach (var item in buckets) { resultList.Add(new Bucket() { Location = item.Location, Name = item.Name, Owner = new Owner() { Name = item.Owner.DisplayName, Id = item.Owner.Id }, CreationDate = item.CreationDate.ToString("yyyy-MM-dd HH:mm:ss"), }); } return(Task.FromResult(resultList)); }
public void TestListBuckets() { OssClient ossClient = GetOssClient(); ListBucketsRequest request = new ListBucketsRequest(); request.RegionId = "cn-north-1"; var result = ossClient.ListBuckets(request).Result; _output.WriteLine(JsonConvert.SerializeObject(result)); }
public static void ListBuckets() { const string accessKeyId = "<your access key id>"; const string accessKeySecret = "<your access key secret>"; const string endpoint = "<valid host name>"; OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { // 1. Try to list all buckets. var buckets = client.ListBuckets(); Console.WriteLine("List all buckets: "); foreach (var bucket in buckets) { Console.WriteLine(bucket.Name + ", " + bucket.Location + ", " + bucket.Owner); } // 2. List buckets by specified conditions, such as prefix/marker/max-keys. var req = new ListBucketsRequest { Prefix = "test", MaxKeys = 3, Marker = "test2" }; var res = client.ListBuckets(req); buckets = res.Buckets; Console.WriteLine("List buckets by page: "); Console.WriteLine("Prefix: " + res.Prefix + ", MaxKeys: " + res.MaxKeys + ", Marker: " + res.Marker + ", NextMarker: " + res.NextMaker); foreach (var bucket in buckets) { Console.WriteLine(bucket.Name + ", " + bucket.Location + ", " + bucket.Owner); } } 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); } }
/// <summary> /// 上传文件到阿里云OSS对像库中 /// </summary> /// <param name="_client">OSS 客户端,用于访问OSS</param> /// <param name="_bucketName">容器名称</param> /// <param name="_filePath">文件路径</param> /// <param name="_vPath">保存到OSS中的路径,不要以“/”开头,示例格式:Uploads/Images/20170226.2356.aaabbb.jpg,注:文件夹会自动创建。</param> /// <returns></returns> public static OssUploadResult UploadFileToOSS(OssClient _client, string _bucketName, string _filePath, string _vPath) { try { #region 检查需上传的文件是否存在 var fileinfo = new System.IO.FileInfo(_filePath); if (!fileinfo.Exists) { throw new Exception($"需要上传的文件不存在,路径:{_filePath}!"); } #endregion #region 检查当前 buckets 容器是否存在,不存在则创建 var buckets = client.ListBuckets(); bool bucketIsExist = false; foreach (var bucket in buckets) { Console.WriteLine($"Name:{bucket.Name},{bucket.Owner},{bucket.Location},{bucket.CreationDate}"); if (bucket.Name == _bucketName) { bucketIsExist = true; break; } } if (!bucketIsExist)//容器 不存在则创建 { CreateBucket(_bucketName); } #endregion _client.PutObject( bucketName: _bucketName, //容器名称 key: _vPath, //保存vPath路径,包括文件名,不要以“/”开头 fileToUpload: _filePath //需要上传的的文件路径 ); return(new OssUploadResult { State = true, Message = "文件上传成功", //FileWLanUrl = $"http://{_bucketName}.{OssConfig.Endpoint}/{_vPath}" FileWLanUrl = $"http://{OssConfig.OssWlanDNS}/{_vPath}", vPath = _vPath }); } catch (Exception ex) { return(new OssUploadResult { State = false, Message = $"文件上传失败,错误消息:{ex.Message},参数值:bucketName:{_bucketName}fileToUpload:{_filePath} Key:{_vPath}" }); } }
/// <summary> /// Gets the containers. /// </summary> /// <returns>System.Collections.Generic.List<System.String>.</returns> public override List <string> GetContainers() { try { var buckets = client.ListBuckets(); return((from one in buckets select one.Name).ToList()); } catch (Exception ex) { throw ex.Handle(); } }
public static void ListBuckets() { const string accessKeyId = "<your access key id>"; const string accessKeySecret = "<your access key secret>"; const string endpoint = "<valid host name>"; OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { // 1. Try to list all buckets. var buckets = client.ListBuckets(); Console.WriteLine("List all buckets: "); foreach (var bucket in buckets) { Console.WriteLine(bucket.Name + ", " + bucket.Location + ", " + bucket.Owner); } // 2. List buckets by specified conditions, such as prefix/marker/max-keys. var req = new ListBucketsRequest {Prefix = "test", MaxKeys = 3, Marker = "test2"}; var res = client.ListBuckets(req); buckets = res.Buckets; Console.WriteLine("List buckets by page: "); Console.WriteLine("Prefix: " + res.Prefix + ", MaxKeys: " + res.MaxKeys + ", Marker: " + res.Marker + ", NextMarker: " + res.NextMaker); foreach (var bucket in buckets) { Console.WriteLine(bucket.Name + ", " + bucket.Location + ", " + bucket.Owner); } } 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); } }
public void DefaultCredentialsProviderNGTest() { try { var ossClient = new OssClient(Config.Endpoint, new Common.Authentication.DefaultCredentialsProvider(null)); ossClient.ListBuckets(); Assert.Fail("Invalid key secret should not initialize OssClient successfully"); } catch (System.Exception e) { Assert.IsTrue(true, e.Message); } }
/// <summary> /// List All Buckets /// </summary> public IEnumerable <Bucket> ListBuckets() { try { var buckets = client.ListBuckets(); return(buckets); } catch (OssException ex) { lastError = ex; return(null); } }
// 1. Try to list all buckets. public static void ListAllBuckets() { try { var buckets = client.ListBuckets(); Console.WriteLine("List all buckets: "); foreach (var bucket in buckets) { Console.WriteLine("Name:{0}", bucket.Name); } } 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); } }
public void InvalidSecurityTokenTest() { try { //Key secret is invalid var ossClient = new OssClient(Config.Endpoint, Config.AccessKeyId, Config.AccessKeySecret, "invalidsecurityToken"); ossClient.ListBuckets(); Assert.Fail("Invalid key secret should not initialize OssClient successfully"); } catch (OssException e) { Assert.AreEqual("InvalidAccessKeyId", e.ErrorCode); } }
public void InvalidAccessKeySecretTest() { try { //Key secret is invalid var ossClient = new OssClient(Config.Endpoint, Config.AccessKeyId, "invalidKeySecret"); ossClient.ListBuckets(); Assert.Fail("Invalid key secret should not initialize OssClient successfully"); } catch (OssException e) { Assert.AreEqual(OssErrorCode.SignatureDoesNotMatch, e.ErrorCode); } }
public void DisabledAccessKeyTest() { try { //Key id/secret is valid but disabled var ossClient = new OssClient(Config.Endpoint, Config.DisabledAccessKeyId, Config.DisabledAccessKeySecret); ossClient.ListBuckets(); Assert.Fail("Disabled access key should not initialize OssClient successfully"); } catch(OssException e) { Assert.AreEqual(OssErrorCode.InvalidAccessKeyId, e.ErrorCode); } }
public void DisabledAccessKeyTest() { try { //Key id/secret is valid but disabled var ossClient = new OssClient(Config.Endpoint, Config.DisabledAccessKeyId, Config.DisabledAccessKeySecret); ossClient.ListBuckets(); Assert.Fail("Disabled access key should not initialize OssClient successfully"); } catch (OssException e) { Assert.AreEqual(OssErrorCode.InvalidAccessKeyId, e.ErrorCode); } }
public async Task refreshBuckets() { try { IEnumerable <Bucket> bucketList = await _ossClient.ListBuckets(); this.Clear(); foreach (Bucket temp in bucketList) { this.Add(temp); } } catch (Exception ex) { throw ex; } }
//列举出所有的存储空间 public void GetAlbums() { var client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { var buckets = client.ListBuckets(); Console.WriteLine("所有相册:"); foreach (var bucket in buckets) { Console.WriteLine("相册名称:{0},地址:{1},物主:{2}", bucket.Name, bucket.Location, bucket.Owner); } } catch (Exception ex) { Console.WriteLine("List bucket failed. {0}", ex.Message); } }
public List <string> GetAllBucket() { var l = new List <string>(); try { var buckets = client.ListBuckets(); foreach (var bucket in buckets) { l.Add(bucket.Name); } } catch (Exception) { } return(l); }
public static void Test() { //.aliyuncs.com /*client: new OSS({ * region: 'oss-cn-shenzhen', * accessKeyId: 'LTAISgT8Qj4MCgAT', * accessKeySecret: 'smtQr62zYeRTHDCZGZ0eseA8CDdBpk', * // bucket: 'swyunfan' * bucket: 'swyunfantesting' * })*/ string endpoint = "oss-cn-shenzhen.aliyuncs.com"; string accessKeyId = "LTAISgT8Qj4MCgAT"; string accessKeySecret = "smtQr62zYeRTHDCZGZ0eseA8CDdBpk"; string bucketName; string objectName; string localFilename; Aliyun.OSS.Common.ClientConfiguration configuration = new Aliyun.OSS.Common.ClientConfiguration(); var client = new OssClient(endpoint, accessKeyId, accessKeySecret, configuration); var list = client.ListBuckets(); var aa = client.GeneratePresignedUri("swyunfantesting", "test100818.jpg"); // 上传文件。 var result = client.PutObject("swyunfantesting", "test100818.jpg", @"G:\resource\e53c868ee9e8e7b28c424b56afe2066d.jpg"); var obj = client.GetObject("swyunfantesting", "test100818.jpg"); using (var requestStream = obj.Content) { byte[] buf = new byte[1024]; var fs = File.Open(@"G:\resource\12313.jpg", FileMode.OpenOrCreate); var len = 0; // 通过输入流将文件的内容读取到文件或者内存中。 while ((len = requestStream.Read(buf, 0, 1024)) != 0) { fs.Write(buf, 0, len); } fs.Close(); } }
public List <string> ListAllBuckets() { try { var buckets = _ossClient.ListBuckets(); return(buckets?.OrderByDescending(d => d.CreationDate).Select(t => t.Name).ToList()); } catch (OssException ex) { _logger.LogError("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); return(new List <string>()); } catch (Exception ex) { _logger.LogError("Failed with error info: {0}", ex.Message); return(new List <string>()); } }
private void tsbConnect_Click(object sender, EventArgs e) { string id = teaccessId.Text.Trim(); string key = teaccesskey.Text.Trim(); if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(key)) { MessageBox.Show("Access id 或 acess key 不能为空。", ""); return; } ossConfig.AccessId = id; ossConfig.AccessKey = key; try { ossClient = new OssClient(id, key); IEnumerable <Bucket> buck = ossClient.ListBuckets(); MessageBox.Show("连接成功。", "info"); setItems(buck); } catch (Exception ex) { MessageBox.Show("连接失败。\r\n 失败原因:" + ex.Message, "error"); } }
private void bw_DoWork(object sender, DoWorkEventArgs e) { alioss alioss = new alioss(SurveyMsg.OSSRegion, false, SurveyMsg.ProjectId); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); this.bw.ReportProgress(20, "检查更新....."); OssClient ossClient = new OssClient(alioss.endpoint, alioss.accessId, alioss.accessKey); bool flag = false; try { using (IEnumerator <Bucket> enumerator = ossClient.ListBuckets().GetEnumerator()) { while (enumerator.MoveNext()) { if (enumerator.Current.Name == alioss.bucketNameUpdate) { flag = true; break; } } } } catch (Exception) { this.bw.ReportProgress(90, GClass0.smethod_0("朤臰跒悮指垨偠ܫ菱懅淡瑒狞")); MessageBox.Show(GClass0.smethod_0("朤臰跒悮指垨偠菱懅淡瑒狞"), GClass0.smethod_0("牌是擶暱"), MessageBoxButton.OK, MessageBoxImage.Asterisk); stopwatch.Stop(); return; } if (!flag) { this.bw.ReportProgress(90, GClass0.smethod_0("孑冠攊冧剭壶规思")); MessageBox.Show(GClass0.smethod_0("孑冠攊冧剭壶规思"), GClass0.smethod_0("牌是擶暱"), MessageBoxButton.OK, MessageBoxImage.Asterisk); stopwatch.Stop(); return; } string str = ""; int num = this.VersionID.ToLower().IndexOf(GClass0.smethod_0("w")); if (num > -1) { str = this.VersionID.Substring(0, num); } else if (this.VersionID.IndexOf(GClass0.smethod_0("浈諗灉")) > -1) { str = GClass0.smethod_0("浈諗灉"); } else if (this.VersionID.IndexOf(GClass0.smethod_0("漗砸灉")) > -1) { str = GClass0.smethod_0("漗砸灉"); } else if (this.VersionID.IndexOf(GClass0.smethod_0("歠帍灉")) > -1) { str = GClass0.smethod_0("歠帍灉"); } else if (this.VersionID.IndexOf(GClass0.smethod_0("辆厫灉")) > -1) { str = GClass0.smethod_0("辆厫灉"); } ObjectListing objectListing = ossClient.ListObjects(alioss.bucketNameUpdate, alioss.bucketDirUpdate + GClass0.smethod_0(".") + str); if (objectListing.ObjectSummaries.Count <OssObjectSummary>() == 0) { this.bw.ReportProgress(90, GClass0.smethod_0("朣昁灏搪拱悴掄䧴")); MessageBox.Show(GClass0.smethod_0("朣昁灏搪拱悴掄䧴"), GClass0.smethod_0("牌是擶暱"), MessageBoxButton.OK, MessageBoxImage.Asterisk); stopwatch.Stop(); return; } string text = ""; string key = ""; string text2 = this.VersionID.ToLower(); string text3 = text2; string text4 = ""; foreach (OssObjectSummary ossObjectSummary in objectListing.ObjectSummaries) { if (!(ossObjectSummary.Key == alioss.bucketDirUpdate + GClass0.smethod_0("."))) { text = ossObjectSummary.Key.Replace(alioss.bucketDirUpdate + GClass0.smethod_0("."), ""); text4 = text.Replace(GClass0.smethod_0("*űɣͳ"), "").ToLower(); key = ossObjectSummary.Key; if (string.Compare(text4, text3) > 0) { text3 = text4; } } } if (text3 == text2) { this.bw.ReportProgress(90, GClass0.smethod_0("彙卄忺緈戩戅掴畋漮")); MessageBox.Show(GClass0.smethod_0("彙卄忺緈戩戅掴畋漮"), GClass0.smethod_0("牌是擶暱"), MessageBoxButton.OK, MessageBoxImage.Asterisk); stopwatch.Stop(); return; } string text5 = Environment.CurrentDirectory + GClass0.smethod_0("VōɧͰѨթ٫ݢࡦढ़"); if (!Directory.Exists(text5)) { Directory.CreateDirectory(text5); } if (!Directory.Exists(text5)) { this.bw.ReportProgress(90, GClass0.smethod_0("曱撴嬲踧ff")); MessageBox.Show(string.Concat(new string[] { GClass0.smethod_0("曤撿灆搡懺杋鄊躈續沀䓰刼䈉噛太"), Environment.NewLine, Environment.NewLine, GClass0.smethod_0("详嘸擻暾噀蓦蹇龎奁埲烌䗣䈎梃䃵嘻"), Environment.NewLine, text5 }), GClass0.smethod_0("曰撳嬳踤"), MessageBoxButton.OK, MessageBoxImage.Asterisk); stopwatch.Stop(); return; } RarFile rarFile = new RarFile(); string path = text5 + text; this.bw.ReportProgress(40, string.Format(GClass0.smethod_0("丂蹵枀䷰Хտسݿࠡ"), text)); FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read); GetObjectRequest getObjectRequest = new GetObjectRequest(alioss.bucketNameUpdate, key); ossClient.GetObject(getObjectRequest, fileStream); fileStream.Close(); this.bw.ReportProgress(80, string.Format(GClass0.smethod_0("觪劃枀䷰Хտسݿࠡ"), text)); this.strRarFile = path; this.strRarOutputFolder = Environment.CurrentDirectory + GClass0.smethod_0("]"); rarFile.Extract(this.strRarFile, this.strRarOutputFolder, this.strRarOutputFolder, this.strRarPassword); this.bw.ReportProgress(95, GClass0.smethod_0("牎昩擰暳䨸福") + text3); this.bw.ReportProgress(95, string.Format(GClass0.smethod_0("夊甋妀愛st蔞揾ܧࡽवଣ痐㴃"), stopwatch.Elapsed.TotalSeconds.ToString(GClass0.smethod_0("Dij")))); stopwatch.Stop(); }