using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using Minio;
using Minio.DataModel;
using Minio.DataModel.Args;
using Minio.DataModel.Encryption;
using Microsoft.WindowsAPICodePack.Dialogs;
using System.IO;
using System.Diagnostics;
using Minio.Exceptions;
using System.Threading;
using System.Security.AccessControl;
namespace Hopetry
{
///
/// test.xaml 的交互逻辑
///
public partial class test : Window
{
private IMinioClient client;
public test()
{
InitializeComponent();
// 配置 MinIO 客户端
client = new Minio.MinioClient()
.WithEndpoint("123.132.248.154:9107") // MinIO 服务器地址
.WithCredentials("KcJPKzOsKfVq20EA4Lyh", "HY7K5EkYpRUphEdINZmAq34tsZD3PMLFTnL85y4N") // 访问密钥和密钥
.Build();
}
#region 多文件上传
private void Button_Click1(object sender, RoutedEventArgs e)
{
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
openFileDialog.Multiselect = true; // 可选择多个文件
openFileDialog.Filter = "All Files (*.*)|*.*";
//openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == true)
{
foreach (string filePath in openFileDialog.FileNames)
{
// 处理选择的文件
UploadFileToMinIOWithProgress(filePath);
}
}
}
private async void UploadFileToMinIOWithProgress(string filePath)
{
try
{
string bucketName = "test";
string objectName = System.IO.Path.GetFileName(filePath);
//判断桶是否存在
var beArgs = new BucketExistsArgs().WithBucket(bucketName);
bool found = await client.BucketExistsAsync(beArgs).ConfigureAwait(false);
if (!found)
{
var mbArgs = new MakeBucketArgs()
.WithBucket(bucketName);
await client.MakeBucketAsync(mbArgs).ConfigureAwait(false);
}
var progress = new Progress(progressReport =>
{
Dispatcher.Invoke(() =>
{
progressBar.Value = progressReport.Percentage;// 更新进度条的值
});
});
PutObjectArgs putObjectArgs = new PutObjectArgs()
.WithBucket(bucketName)
.WithObject(objectName)
.WithFileName(filePath)
//.WithContentType("application/octet-stream")
.WithProgress(progress);
// 上传文件并提供进度反馈
await client.PutObjectAsync(putObjectArgs);
MessageBox.Show("文件上传成功!");
}
catch (Exception ex)
{
MessageBox.Show($"上传失败: {ex.Message}");
}
}
#endregion
#region 文件夹选择
private void Button_Click(object sender, RoutedEventArgs e)
{
// 打开文件夹选择对话框
var dialog = new CommonOpenFileDialog
{
IsFolderPicker = true,
Title = "请选择上传文件"
};
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
string folderPath = dialog.FileName;
// 处理选择的文件
UploadFileToMinIO(folderPath);
}
}
private async void UploadFileToMinIO(string folderPath)
{
try
{
string bucketName = "test";
// 检查存储桶是否存在,如果不存在则创建
var beArgs = new BucketExistsArgs().WithBucket(bucketName);
bool found = await client.BucketExistsAsync(beArgs).ConfigureAwait(false);
if (!found)
{
var mbArgs = new MakeBucketArgs()
.WithBucket(bucketName);
await client.MakeBucketAsync(mbArgs).ConfigureAwait(false);
}
// 获取文件夹中的所有文件
var files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
int totalFiles = files.Length;
int uploadedFiles = 0;
// 更新UI显示总文件数
Dispatcher.Invoke(() => StatusText.Text = $"Uploading {totalFiles} files...");
// 遍历文件并上传
foreach (var filePath in files)
{
string objectName = filePath.Substring(folderPath.Length + 1).Replace('\\', '/');
; // 保留文件夹结构 //重点注意后面的Replace
var putObjectArgs = new PutObjectArgs()
.WithBucket(bucketName)
.WithObject(objectName)
.WithFileName(filePath);
await client.PutObjectAsync(putObjectArgs);
uploadedFiles++;
int progress = (int)((double)uploadedFiles / totalFiles * 100);
// 更新UI显示上传进度
Dispatcher.Invoke(() =>
{
progressBar.Value = progress;
StatusText.Text = $"Uploaded {uploadedFiles} of {totalFiles} files...";
});
}
// 上传完成
Dispatcher.Invoke(() =>
{
StatusText.Text = "Upload completed!";
MessageBox.Show("All files uploaded successfully!");
// 判断开关状态
if (ShutdownCheckBox.IsChecked == true)
{
// 如果开关状态为“开”,执行Shutdown方法
Shutdown();
}
});
}
catch (Exception ex)
{
Dispatcher.Invoke(() =>
{
StatusText.Text = "Upload failed!";
MessageBox.Show($"Error uploading files: {ex.Message}");
});
}
}
// 关机方法
private void Shutdown()
{
try
{
// 使用shutdown命令关机
Process.Start("shutdown", "/s /t 0");
}
catch (System.ComponentModel.Win32Exception ex)
{
MessageBox.Show($"关机失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
#endregion
private void progressBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs e)
{
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
try
{
string bucketName = "test";
// 检查存储桶是否存在,如果不存在则创建
var beArgs = new BucketExistsArgs().WithBucket(bucketName);
// Check whether 'mybucket' exist or not.
bool found = await client.BucketExistsAsync(beArgs).ConfigureAwait(false);
if (found)
{
// List all incomplete multipart upload of objects in 'mybucket'
ListIncompleteUploadsArgs listArgs = new ListIncompleteUploadsArgs()
.WithBucket("test")
.WithRecursive(true);
IAsyncEnumerable observable = client.ListIncompleteUploadsEnumAsync(listArgs);
//IDisposable subscription = observable.Subscribe(
// item => Console.WriteLine("OnNext: {0}", item.Key),
// ex => Console.WriteLine("OnError: {0}", ex.Message),
// () => Console.WriteLine("OnComplete: {0}"));
await foreach (var upload in observable)
{
// 在这里查看每个 Upload 对象
Console.WriteLine($"Upload ID: {upload.UploadId}, Object Name: {upload.Key}");
var statObjectArgs = new StatObjectArgs()
.WithBucket(bucketName)
.WithObject(upload.Key);
// Get object metadata if it exists
var objectStat = await client.StatObjectAsync(statObjectArgs);
}
}
else
{
Console.WriteLine("mybucket does not exist");
}
}
catch (MinioException ex)
{
Console.WriteLine("Error occurred: " + ex);
}
}
}
}