Infrastructure/OpenAuth.App/ServiceApp/Job/FileMonitor.cs

218 lines
6.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System.Text;
using Infrastructure.Helpers;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NUnit.Framework;
using OpenAuth.Repository.Domain;
using Quartz;
namespace OpenAuth.App.ServiceApp.Job;
class FileMonitor
{
[Test]
public async System.Threading.Tasks.Task Execute()
{
var builder = new ConfigurationBuilder()
.SetBasePath("D:\\vs\\project_git\\Infrastructure\\OpenAuth.WebApi")
.AddJsonFile("appsettings.json");
// 构建配置
var configuration = builder.Build();
// 目标目录
var targetDirectory = configuration.GetSection("Insight:Dir").Value;
//var targetDirectory = ConfigHelper.GetConfigRoot().GetSection("Insight:Dir").Value;
var tifExtensions = new[] { ".tif", ".tfw", ".ovr", ".aux", ".xml" };
// 相关文件扩展名
var shpExtensions = new[] { ".shp", ".shx", ".dbf", ".prj", ".cpg" };
var targetExtensions = new[] { ".tif", ".shp" };
// 遍历目标目录,查找所有 .shp 文件
//string[] shpFiles = Directory.GetFiles(targetDirectory, "*.shp", SearchOption.AllDirectories);
/*var shpFiles = Directory.EnumerateFiles(targetDirectory)
.Where(file => targetExtensions.Any(ext => file.EndsWith(ext, StringComparison.OrdinalIgnoreCase)));*/
DirectoryInfo directoryInfo = new DirectoryInfo(targetDirectory);
FileInfo[] shpFiles = directoryInfo.EnumerateFiles("*", SearchOption.AllDirectories)
.Where(file => targetExtensions.Contains(file.Extension.ToLower()))
.ToArray();
foreach (var fileInfo in shpFiles)
{
var file = fileInfo.FullName;
var baseFileName = Path.GetFileNameWithoutExtension(file);
var directory = Path.GetDirectoryName(file);
if (file.EndsWith(".shp"))
{
if (IsShpFileComplete(directory, baseFileName, shpExtensions))
{
var result = await AddInsAiShp(file);
Console.WriteLine("shp提交结果" + result);
}
}
else
{
if (IsTifFileComplete(directory, baseFileName, tifExtensions))
{
Console.WriteLine($"{baseFileName} 及其相关文件已完整拷贝到 {targetDirectory}");
await AddInsTif(file);
}
}
}
}
public static bool IsTifFileComplete(string targetDirectory, string baseFileName, string[] extensions)
{
foreach (var extension in extensions)
{
string targetFilePath = Path.Combine(targetDirectory, baseFileName + extension);
if (!File.Exists(targetFilePath))
{
return false;
}
// 检查文件是否仍在写入
if (IsFileLocked(new FileInfo(targetFilePath)))
{
return false;
}
}
return true;
}
public static bool IsShpFileComplete(string targetDirectory, string baseFileName, string[] extensions)
{
foreach (var extension in extensions)
{
string targetFilePath = Path.Combine(targetDirectory, baseFileName + extension);
if (!File.Exists(targetFilePath))
{
return false;
}
// 检查文件是否仍在写入
if (IsFileLocked(new FileInfo(targetFilePath)))
{
return false;
}
}
return true;
}
public static bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (IOException)
{
// 文件被锁定
return true;
}
finally
{
if (stream != null)
{
stream.Close();
}
}
// 文件未被锁定
return false;
}
private static async Task<bool> AddInsTif(string tifPath)
{
using var client = new HttpClient();
var url = "http://localhost:5007/api/InsTif/Insert";
var tifName = Path.GetFileName(tifPath);
var tifDate = new DirectoryInfo(tifPath).Parent?.Name;
if (string.IsNullOrEmpty(tifDate))
{
throw new Exception("获取不到日期目录");
}
var areaName = new DirectoryInfo(tifPath).Parent?.Parent?.Name;
var currentTime = DateTime.Now;
var tifRecord = new InsTif
{
TifName = tifName,
TifPath = tifPath,
Remark = "备注",
TifDate = DateTime.ParseExact(tifDate, "yyyy年MM月", null),
CreateTime = currentTime,
UpdateTime = currentTime,
AreaName = areaName,
PlotName = "地块",
AreaId = "areaid",
AreaNum = Convert.ToDecimal(0)
};
// 将数据对象序列化为 JSON 字符串
var json = JsonConvert.SerializeObject(tifRecord);
// 创建 HttpContent 对象
var content = new StringContent(json, Encoding.UTF8, "application/json");
// 发送 POST 请求
var response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
return true;
}
return false;
}
private static async Task<bool> AddInsAiShp(String shpPath)
{
using var client = new HttpClient();
var url = "http://localhost:5007/api/InAiShp/Insert";
// 县区/shp名称
var fileName = Path.GetFileName(shpPath);
var dateStr = fileName.Substring(0, 6);
var date = DateTime.ParseExact(dateStr, "yyMMdd", null);
var areaName = new DirectoryInfo(shpPath).Parent?.Parent?.Name;
var shpInfo = ShpUtil.GetShpInfo(shpPath);
var insAishp = new InsAishp();
var currentTime = DateTime.Now;
//insAishp.Id = Guid.NewGuid().ToString();
insAishp.ShpPath = shpPath;
insAishp.ShpName = fileName;
insAishp.ShpDate = date;
// 面积
insAishp.AreaNum = 0;
insAishp.PlotName = "地块名称";
insAishp.AreaId = "areaId";
// 地区名称
insAishp.AreaName = areaName;
// 包含图斑数量
insAishp.ShpCount = shpInfo.GetType().GetProperty("Count").GetValue(shpInfo);
;
insAishp.CreateTime = currentTime;
insAishp.UpdateTime = currentTime;
insAishp.Remark = "备注";
var json = JsonConvert.SerializeObject(insAishp);
// 创建 HttpContent 对象
var content = new StringContent(json, Encoding.UTF8, "application/json");
// 发送 POST 请求
var response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
return true;
}
return false;
}
}