当前位置:网站首页>C Alibaba cloud OSS file upload, download and other operations (unity is available)
C Alibaba cloud OSS file upload, download and other operations (unity is available)
2022-07-07 15:43:00 【sky954260193】
link : Official website SDK download .
OSS Global configuration
public class OssConfig
{
public const string AccessKeyId = "xxxxxxxxx";
public const string AccessKeySecret = "xxxxxxxxxxx";
public const string EndPoint = "xxxxxxxxxxxx";
public const string Bucket = "xxxxxxxxxxxxxx";
}
OSS Local examples
using Aliyun.OSS;
namespace AliyunOSS
{
public class LocalOSSClient
{
private static OssClient _ossClient;
private static readonly object _synclock = new object();
public static OssClient OssClient
{
get
{
if (_ossClient == null)
{
lock (_synclock)
{
if (_ossClient == null)
{
_ossClient = new OssClient(OssConfig.EndPoint, OssConfig.AccessKeyId,
OssConfig.AccessKeySecret);
}
}
}
return _ossClient;
}
}
}
}
Upload files
using System;
using System.Threading;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using System.IO;
namespace AliyunOSS
{
public class AliyunOSSUpLoader
{
public static void UpLoad(string fullFilePath, string ossPath, Action complete, Action<float> process = null)
{
PutObjectWithProcessByThread(fullFilePath, ossPath, complete, process);
}
public void UpLoad(string fullFilePath, string ossPath, Action complete)
{
PutObjectWithProcessByThread(fullFilePath, ossPath, complete);
}
private static void PutObjectWithProcessByThread(string fullFilePath, string ossPath, Action complete, Action<float> action = null)
{
Thread putLocalThread = null;
putLocalThread = new Thread(() =>
{
try
{
using (var fs = File.Open(fullFilePath, FileMode.Open))
{
PutObjectRequest putObjectRequest = new PutObjectRequest(OssConfig.Bucket, ossPath, fs);
putObjectRequest.StreamTransferProgress += (obg, args) =>
{
float putProcess = (args.TransferredBytes * 100 / args.TotalBytes) / 100.0f;
action?.Invoke(putProcess);
if (putProcess >= 1)
{
complete?.Invoke();
putObjectRequest.StreamTransferProgress = null;
}
};
LocalOSSClient.OssClient.PutObject(putObjectRequest);
}
}
catch (OssException e)
{
Console.WriteLine(" Upload error :" + e);
}
catch (Exception e)
{
Console.WriteLine(" Upload error :" + e);
}
finally
{
putLocalThread.Abort();
}
});
putLocalThread.Start();
}
}
Upload files URL get
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AliyunOSS
{
/// <summary>
/// Get the download link of the file through the file name
/// </summary>
public class OssUrlUtility
{
public static string GetFileUrl(string fileFullName)
{
string url = "http://" + OssConfig.Bucket + "." + OssConfig.EndPoint + "/" + fileFullName;
return url;
}
}
}
File download
using System;
using System.IO;
namespace AliyunOSS
{
public class OSSDownLoadHandler
{
/// <summary>
///
/// </summary>
/// <param name="objName"> OOS The full path of the file to be downloaded stored in the server </param>
/// <param name="saveFullPathWithExtension"> File path stored locally , Suffixes are required </param>
public static void DownLoadFiles(string objName, string saveFullPathWithExtension)
{
var client = LocalOSSClient.OssClient;
try
{
var obj = client.GetObject(OssConfig.Bucket, objName);
using (var requestStream = obj.Content)
{
byte[] buf = new byte[1024];
var fs = File.Open(saveFullPathWithExtension, FileMode.OpenOrCreate);
var len = 0;
while ((len = requestStream.Read(buf, 0, 1024)) != 0)
{
fs.Write(buf, 0, len);
}
fs.Close();
}
Console.WriteLine("Get object succeeded:" + saveFullPathWithExtension);
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Get object failed. {0}", ex.Message));
}
}
}
}
file information
using System;
using System.Collections.Generic;
using Aliyun.OSS;
using Aliyun.OSS.Common;
namespace AliyunOSS
{
public class OSSFiles
{
/*ListObjectsRequest Parameters : objectSummaries Limit the returned file meta information . prefix The prefix of this query result . delimiter A character that groups file names . marker Indicate the starting point of the listed documents . maxKeys List the maximum number of files . nextMarker Next time, list the starting point of the file . isTruncated Indicates whether the enumeration file is truncated . There is no truncation after enumeration , The return value is false. There is truncation before enumeration , The return value is true. commonPrefixes With delimiter ending , A collection of files with a common prefix . encodingType Indicate the type of encoding used in the returned result .*/
/// <summary>
/// Simple column retrieval 100 strip
/// </summary>
public static void ShowSampleOSSFileList()
{
var client = LocalOSSClient.OssClient;
try
{
var listObjectsRequest = new ListObjectsRequest(OssConfig.Bucket);
// Simply list the files in the storage space , Default return 100 Bar record .
var result = client.ListObjects(listObjectsRequest);
foreach (var summary in result.ObjectSummaries)
{
Console.WriteLine(string.Format("File name:{0}", summary.Key));
}
}
catch (Exception ex)
{
Console.WriteLine(string.Format("List objects failed. {0}", ex.Message));
}
}
public static void ShowSpecifyFiles(int maxKeys = 200)
{
var client = LocalOSSClient.OssClient;
try
{
var listObjectsRequest = new ListObjectsRequest(OssConfig.Bucket)
{
// Maximum return 200 Bar record .
MaxKeys = maxKeys,
};
var result = client.ListObjects(listObjectsRequest);
Console.WriteLine("List objects succeeded");
foreach (var summary in result.ObjectSummaries)
{
Console.WriteLine(summary.Key);
}
}
catch (Exception ex)
{
Console.WriteLine(string.Format("List objects failed, {0}", ex.Message));
}
}
public static void ShowPrefixFiles(string prefix)
{
var client = LocalOSSClient.OssClient;
try
{
var keys = new List<string>();
ObjectListing result = null;
string nextMarker = string.Empty;
do
{
var listObjectsRequest = new ListObjectsRequest(OssConfig.Bucket)
{
Marker = nextMarker,
MaxKeys = 100,
Prefix = prefix,
};
result = client.ListObjects(listObjectsRequest);
foreach (var summary in result.ObjectSummaries)
{
keys.Add(summary.Key);
}
nextMarker = result.NextMarker;
} while (result.IsTruncated);
foreach (var fSummary in result.ObjectSummaries)
{
Console.WriteLine(fSummary.Key);
}
Console.WriteLine(string.Format("List objects of bucket:{0} succeeded ", OssConfig.Bucket));
}
catch (OssException ex)
{
Console.WriteLine(string.Format("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(string.Format("Failed with error info: {0}", ex.Message));
}
}
public static void ShowSpecifyExtensionFiles(string maker)
{
var client = LocalOSSClient.OssClient;
try
{
var keys = new List<string>();
ObjectListing result = null;
string nextMarker = maker;
do
{
var listObjectsRequest = new ListObjectsRequest(OssConfig.Bucket)
// If you want to increase the number of returned files , You can modify MaxKeys Parameters , Or use Marker Parameters are read in several times .
{
Marker = nextMarker,
MaxKeys = 100,
};
result = client.ListObjects(listObjectsRequest);
foreach (var summary in result.ObjectSummaries)
{
keys.Add(summary.Key);
}
nextMarker = result.NextMarker;
// If IsTruncated by true, NextMarker Will be the starting point for the next reading .
} while (result.IsTruncated);
foreach (var fSummary in result.ObjectSummaries)
{
Console.WriteLine(fSummary.Key);
}
Console.WriteLine(string.Format("List objects of bucket:{0} succeeded ", OssConfig.Bucket));
}
catch (OssException ex)
{
Console.WriteLine(string.Format("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(string.Format("Failed with error info: {0}", ex.Message));
}
}
}
}
File operations
using System;
using System.Collections.Generic;
using Aliyun.OSS;
using Aliyun.OSS.Common;
namespace AliyunOSS
{
public class AliyunOSSHelper
{
/// <summary>
/// Delete single file
/// </summary>
/// <param name="objectName"></param>
public static void DeleteFile(string objectName)
{
var client = LocalOSSClient.OssClient;
try
{
// Delete file .
client.DeleteObject(OssConfig.Bucket, objectName);
Console.WriteLine("Delete object succeeded");
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Delete object failed. {0}", ex.Message));
}
}
/// <summary>
///
/// </summary>
/// <param name="files"></param>
/// <param name="quietMode"> Set to verbose mode , Return to the list of all deleted files .</param>
public static void DeleteMultiFiles(List<string> files, bool quietMode = false)
{
var client = LocalOSSClient.OssClient;
try
{
var request = new DeleteObjectsRequest(OssConfig.Bucket, files, quietMode);
var result = client.DeleteObjects(request);
if ((!quietMode) && (result.Keys != null))
{
foreach (var obj in result.Keys)
{
Console.WriteLine(string.Format("Delete successfully : {0} ", obj.Key));
}
}
Console.WriteLine("Delete objects succeeded");
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Delete objects failed. {0}", ex.Message));
}
}
public static bool ExistFile(string objectName)
{
bool exist = false;
try
{
exist = LocalOSSClient.OssClient.DoesObjectExist(OssConfig.Bucket, objectName);
Console.WriteLine("Object exist ? " + exist);
return exist;
}
catch (OssException ex)
{
Console.WriteLine(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId));
return exist;
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Failed with error info: {0}", ex.Message));
return exist;
}
}
}
}
边栏推荐
- 如何在opensea批量发布NFT(Rinkeby测试网)
- 【數字IC驗證快速入門】26、SystemVerilog項目實踐之AHB-SRAMC(6)(APB協議基本要點)
- #HPDC智能基座人才发展峰会随笔
- Asynchronous application of generator function
- What are PV and UV? pv、uv
- 微信小程序 01
- Vertex shader to slice shader procedure, varying variable
- HW primary flow monitoring, what should we do
- 15. Using the text editing tool VIM
- Window环境下配置Mongodb数据库
猜你喜欢
![[server data recovery] a case of RAID data recovery of a brand StorageWorks server](/img/aa/6d820d97e82df1d908dc7aa78fc8bf.png)
[server data recovery] a case of RAID data recovery of a brand StorageWorks server

Zhongang Mining: Fluorite continues to lead the growth of new energy market

Spin animation of Cocos performance optimization

Getting started with webgl (4)
![[Data Mining] Visual Pattern Mining: Hog Feature + cosinus Similarity / K - means Clustering](/img/a4/7320f5d266308f6003cc27964e49f3.png)
[Data Mining] Visual Pattern Mining: Hog Feature + cosinus Similarity / K - means Clustering

【數據挖掘】視覺模式挖掘:Hog特征+餘弦相似度/k-means聚類
![[deep learning] image hyperspectral experiment: srcnn/fsrcnn](/img/84/114fc8f0875b82cc824e6400bcb06f.png)
[deep learning] image hyperspectral experiment: srcnn/fsrcnn

知否|两大风控最重要指标与客群好坏的关系分析
![[quickstart to Digital IC Validation] 20. Basic syntax for system verilog Learning 7 (Coverage Driven... Including practical exercises)](/img/d3/cab8a1cba3c8d8107ce4a95f328d36.png)
[quickstart to Digital IC Validation] 20. Basic syntax for system verilog Learning 7 (Coverage Driven... Including practical exercises)
![[deep learning] semantic segmentation experiment: UNET network /msrc2 dataset](/img/69/9dadeb92f8d6299250a894690c2845.png)
[deep learning] semantic segmentation experiment: UNET network /msrc2 dataset
随机推荐
[quick start of Digital IC Verification] 26. Ahb-sramc of SystemVerilog project practice (6) (basic points of APB protocol)
【數據挖掘】視覺模式挖掘:Hog特征+餘弦相似度/k-means聚類
Starting from 1.5, build a microservice framework link tracking traceid
[quickstart to Digital IC Validation] 20. Basic syntax for system verilog Learning 7 (Coverage Driven... Including practical exercises)
Nacos conformance protocol cp/ap/jraft/distro protocol
全日制研究生和非全日制研究生的区别!
2. Heap sort "hard to understand sort"
What is Base64?
【微信小程序】Chapter(5):微信小程序基础API接口
Ida Pro reverse tool finds the IP and port of the socket server
Use cpolar to build a business website (2)
【数字IC验证快速入门】25、SystemVerilog项目实践之AHB-SRAMC(5)(AHB 重点回顾,要点提炼)
一大波开源小抄来袭
大表delete删数据导致数据库异常解决
Introduction of mongod management database method
银行需要搭建智能客服模块的中台能力,驱动全场景智能客服务升级
webgl_ Graphic transformation (rotation, translation, zoom)
[quick start of Digital IC Verification] 22. Ahb-sramc of SystemVerilog project practice (2) (Introduction to AMBA bus)
[Lanzhou University] information sharing of postgraduate entrance examination and re examination
微信小程序 01