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

213 lines
8.6 KiB

3 years ago
using System;
using System.IO;
using S3Demo.Model.Uploader;
using System.Threading;
3 years ago
using System.Linq;
3 years ago
namespace S3Demo
{
3 years ago
public class Program
3 years ago
{
3 years ago
private static string[] paths = { @"D:\ClientDir" };
private static string suffix = "*.png";
public static void Main()
3 years ago
{
try
3 years ago
{
#region 目录监控
foreach (var path in paths)
{
FileSystemWatcher watch = new FileSystemWatcher()
{
Path = path,
Filter = suffix,
3 years ago
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName,
};
watch.Created += OnCreated;
watch.Error += OnError;
// 开始监控
watch.EnableRaisingEvents = true;
}
3 years ago
#endregion
#region 保存至数据库
//string s3Flag = ObjectModel.Putobjectswithtags(bucketName, S3Path, e.FullPath, tags, credentials, conf).Result;
//if (s3Flag.Equals("OK"))
//{
//保存至数据库
//using (var dev = new CodeFirstDbContext())
// {
// dev.UploadFinishs.Add(new UploadFinish()
// {
// UploaderID = lineName,
// Tag = sn,
// CreateAt = dt_fomat,
// RetryAt = DateTime.ParseExact(now, "yyyyMMddHHmmssfff", System.Globalization.CultureInfo.CurrentCulture),
// RetryCount = 1,
// RequestData = S3Path
// });
// int dbFlag = dev.SaveChanges();//1: 保存至数据库成功,否则保存失败
// //TODO: 请求接口
// //ReqData req = new ReqData();
// //RespData resp = new RespData();
// //req.s3Flag = s3Flag;
// //req.dbFlag = dbFlag;
// //resp = JsonConvert.DeserializeObject<RespData>(HttpModel.PostUrl(url, JsonConvert.SerializeObject(req)));
// //Console.WriteLine("resp: " + resp.code + " " + resp.message);
// }
//Console.WriteLine("S3对象存储路径: " + bucketName + "/" + S3Path);
//}
//else
//{
// Console.WriteLine("上传未完成");
//}
3 years ago
//Uploader<string> uploader = new Uploader<string>("字符串测试", new UploaderOperator());
//for (var i = 0; i < 5; i++)
3 years ago
//{
// uploader.AddUploadRequest($"hello{i}", $"tag{i}");
3 years ago
//}
#endregion
3 years ago
#region S3相关测试
/*
//creating Bucket
//await CreateBucket.CreatingBucket("minio/bu29", credentials, conf);
3 years ago
//upload Dir
3 years ago
string dirPath = @"C:\Users\song\Pictures\Saved Pictures\";
string suffix = "*.png";
//await UploadDirMPUHighLevelAPI.Uploaderdir(bucketName, dirPath, suffix, credentials, conf);
3 years ago
//upload File
string keyName = "logo.png";
3 years ago
//await UploadFileMPUHighLevelAPI.Uploaderfile(bucketName, keyName, dirPath, credentials, conf);
3 years ago
//list Objects
//await ListObjects.Listingobjects(bucketName, credentials, conf);
//upload Object With Tag
3 years ago
string filaPath = @"C:\Users\song\Pictures\Saved Pictures\" + keyName;
String[] tags = new String[] { "SN123456", DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:sszzz"), "AB023" };
3 years ago
//await ObjectModel.Putobjectswithtags(bucketName, keyName, filaPath, tags, credentials, conf);
//read Object
//await ObjectModel.Readobjectdata(bucketName, keyName, credentials, conf);
3 years ago
3 years ago
//isExist Bucket
//从"minio/test"中取出存储桶名
var _bucketName = bucketName.Split('/')[1];
//此处传入bucketName: "test"
//var flag = await BucketModel.isExistBucket(_bucketName, credentials, conf);
//if (flag)
//{
// Console.WriteLine("exist");
//}
//else
//{
// Console.WriteLine("not exist");
// //docker创建buckeyt时此处传入BucketName: "minio/test"
// //play.min.io创建buckeyt时传入BucketName: "test"
// await BucketModel.CreateBucket(bucketName, credentials, conf);
//}
////删除桶docker删除桶"minio/test"; play.min.io删除桶"test"
//await new AmazonS3Client(credentials, conf).DeleteBucketAsync(bucketName);
//Console.WriteLine("delete bucket " + bucketName);
*/
3 years ago
#endregion
3 years ago
}
catch (Exception ex)
{
Console.WriteLine($"Main: {ex.Message}");
3 years ago
}
Console.ReadKey();
}
/// <summary>
/// 创建文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
3 years ago
private static void OnCreated(object sender, FileSystemEventArgs e)
{
3 years ago
//Waiting(e.FullPath);
// 如果创建过程中就上传1、重传机制会载入重传队列2、也可手动添加固定延时等待创建完成在上传
DisposeFile(e.FullPath);
}
/// <summary>
/// 等待onCreated事件处理完成
/// </summary>
/// <param name="path">被创建的文件路径</param>
private static void Waiting(string path)
{
try
{
FileInfo fi;
fi = new FileInfo(path);
long len1, len2;
len2 = fi.Length;
do
3 years ago
{
len1 = len2;
Thread.Sleep(1000);//等待1秒钟
fi.Refresh();//这个语句不能漏了
len2 = fi.Length;
} while (len1 < len2);
}
catch { }
}
/// <summary>
/// 处理文件
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
3 years ago
private static void DisposeFile(string path)
{
// D:\ClientDir\line01\AOI\20211129\085023891P107CN14T00001.png
string lineName = Path.GetDirectoryName(path).Split('\\')[2];
string equipmentName = Path.GetDirectoryName(path).Split('\\')[3];
string date = Path.GetDirectoryName(path).Split('\\')[4];
string fileName = Path.GetFileName(path);
string datetime = date + fileName.Substring(0, 9);
string dt_fomat = DateTime.ParseExact(datetime, "yyyyMMddHHmmssfff", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy-MM-dd HH:mm:ss:fff");
string sn = fileName.Substring(9, 14);
string now = DateTime.Now.ToString("yyyyMMddHHmmssfff");
String[] tags = new String[] { sn, dt_fomat };
string S3Path = lineName + "/" + equipmentName + "/" + date + "/" + fileName;
3 years ago
var uploadModel = new S3UploadModel { Keyname = S3Path, Path = path, Tags = tags.ToList() };
S3Uploader.Instance().AddUploadTask(uploadModel, sn);
}
/// <summary>
/// 出现错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void OnError(object sender, ErrorEventArgs e) =>
PrintException(e.GetException());
/// <summary>
/// 打印错误
/// </summary>
/// <param name="ex"></param>
private static void PrintException(Exception ex)
{
if (ex != null)
{
Console.WriteLine($"Message: {ex.Message}");
Console.WriteLine("Stacktrace:");
Console.WriteLine(ex.StackTrace);
Console.WriteLine();
PrintException(ex.InnerException);
}
}
3 years ago
}
}