You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

132 lines
4.3 KiB
C#

3 months ago
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Minio.Exceptions;
using Minio;
using Microsoft.Extensions.Configuration;
using Minio.DataModel.Args;
using Minio.DataModel;
namespace Infrastructure.CloudSdk.minio;
public class MinioService
{
private IMinioClient _minioClient;
public readonly string _bucketName = null;
public MinioService()
{
InitializeMinIOClient();
EnsureBucketExistsAsync(_bucketName).Wait();
}
private void InitializeMinIOClient()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("global.json", optional: false, reloadOnChange: true);
// 构建配置
var config = builder.Build();
_minioClient = new MinioClient()
.WithEndpoint(config["Minio:Endpoint"])
.WithCredentials(config["Minio:AccessKey"], config["Minio:SecretKey"])
.Build();
}
/// <summary>
/// 创建存储桶(如果不存在)
/// </summary>
public async Task CreateBucketIfNotExists(string _bucketName)
{
var existsArgs = new BucketExistsArgs().WithBucket(_bucketName);
bool found = await _minioClient.BucketExistsAsync(existsArgs);
if (!found)
{
var makeArgs = new MakeBucketArgs().WithBucket(_bucketName);
await _minioClient.MakeBucketAsync(makeArgs);
Console.WriteLine($"Bucket {_bucketName} created.");
}
}
public async Task EnsureBucketExistsAsync(string bucketName)
{
var existsArgs = new BucketExistsArgs().WithBucket(bucketName);
var x = await _minioClient.BucketExistsAsync(existsArgs);
Console.WriteLine($" {bucketName} exist status: " + x);
// 如果存储桶不存在,则创建存储桶
if (!x)
{
var makeArgs = new MakeBucketArgs().WithBucket(bucketName);
await _minioClient.MakeBucketAsync(makeArgs);
}
}
/// <summary>
/// 下载文件
/// </summary>
public async Task DownLoadObject(string bucketName, string objectKey, string localDir, string objectETag,
CancellationToken token = default)
{
var index = objectKey.LastIndexOf("/", StringComparison.Ordinal);
if (index > 0)
{
var dir = Path.Combine(localDir, objectKey.Substring(0, index));
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
var localPath = Path.Combine(localDir, objectKey.Replace('/', Path.DirectorySeparatorChar));
var getArgs = new GetObjectArgs()
.WithBucket(string.IsNullOrEmpty(bucketName) ? _bucketName : bucketName)
.WithObject(objectKey)
.WithFile(localPath);
var stat = await _minioClient.GetObjectAsync(getArgs, token);
}
/// <summary>
/// 列出所有对象
/// </summary>
public async Task<IAsyncEnumerable<Item>> ListAllObject(string bucketName, string prefix, bool recursive,
CancellationToken token = default)
{
// Just list of objects
// Check whether 'mybucket' exists or not.
if (string.IsNullOrEmpty(bucketName))
{
bucketName = _bucketName;
}
var existsArgs = new BucketExistsArgs().WithBucket(bucketName);
var found = await _minioClient.BucketExistsAsync(existsArgs, token);
if (found)
{
var args = new ListObjectsArgs()
.WithBucket(bucketName)
.WithPrefix(prefix)
.WithRecursive(recursive);
return _minioClient.ListObjectsEnumAsync(args, token);
}
Console.WriteLine("mybucket does not exist");
throw new Exception("bucket not found");
}
/// <summary>
/// 删除文件
/// </summary>
public async Task DeleteFile(string objectName)
{
try
{
var deleteargs = new RemoveObjectArgs().WithBucket(_bucketName).WithObject(objectName);
await _minioClient.RemoveObjectAsync(deleteargs);
Console.WriteLine($"File {objectName} deleted.");
}
catch (MinioException ex)
{
Console.WriteLine($"MinIO Exception: {ex.Message}");
}
}
}