Files
CJLR-Analysis/Analysis/BaseUnit/FileSorter.cs
T
HM-CN\zhengxuan.zhang 89ab9cce88 #005 增加必要的整理
2025-08-06 16:41:47 +08:00

233 lines
6.4 KiB
C#

using BaseFunction;
using NSAnalysis.DAL;
using NSAnalysis.Model;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace NSAnalysis.BaseUnit
{
public class FileSorter
{
public CjlrDAL _dal = new CjlrDAL();
//定义读取的位置
public int readRowIndex = 2; // 默认读取第3行(从0开始计数)
public int readColIndex = 1; // 默认读取第2列(从0开始计数)
public FileSorter()
{
}
public void ProcessFiles()
{
var tasks = GetTaskRecords();
foreach (DataRow task in tasks.Rows)
{
string modelName = task["modelsName"].ToString();
string modelCode = task["modelsCode"].ToString();
string position = task["position"].ToString();
string sourceDir = task["sourceFile"].ToString();
string targetDir = task["targetFile"].ToString();
// 打印信息
MyBase.TraceWriteLine($"Processing Task - Source: {sourceDir}, Target: {targetDir}, ModelCode: {modelCode} Position: {position}");
if (Directory.Exists(sourceDir))
{
ProcessDirectory(sourceDir, targetDir, modelCode, modelName,position);
}
else
{
MyBase.TraceWriteLine($"源文件地址不存在或错误: {sourceDir}");
//记录到数据库
try
{
//插入分发详情
CjlrTaskReleaseDetailModel detailModel = new CjlrTaskReleaseDetailModel
{
ModelsName = modelName, // 这里可以根据需要填写车型名称
ModelsCode = modelCode,
Position = position, // 这里可以根据需要填写位置
SourceFile = "",
TargetFile = "",
TaskFileName = "",
TaskStatus = 2, // 假设1表示已处理, 2表示未处理
TaskDetail = $"源文件地址不存在或错误: {sourceDir}",
CreateDate = DateTime.Now
};
_dal.InsertTaskDetail(detailModel);
}
catch (Exception ex)
{
MyBase.TraceWriteLine($"记录错误到数据库失败: {ex.Message}");
}
finally
{
MyBase.TraceWriteLine($"源文件地址不存在或错误: {sourceDir}");
}
}
}
}
private DataTable GetTaskRecords()
{
SQLHelper.connStr = DatabaseDfn.SqlConnectStr();
DataTable dt = _dal.SelectTaskByCondition("", "", "start");
//打印 dt
PrintDataTable(dt);
if (dt == null || dt.Rows.Count == 0)
{
MyBase.TraceWriteLine("No tasks found.");
return null;
}
return dt;
}
private void ProcessDirectory(string sourceDir, string targetDir, string modelCode, string modelName, string position )
{
// 匹配信息
string matchStr = $"{modelCode}_{position}";
MyBase.TraceWriteLine($"Matching files with: {matchStr}");
// 判断目标目录是否存在,如果不存在记录到日志
// 确保目标目录存在
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir);
MyBase.TraceWriteLine($"Created target directory: {targetDir}");
}
// 遍历源目录中的所有CSV文件
foreach (string file in Directory.GetFiles(sourceDir, "*.csv"))
{
// 打印正在处理的文件
MyBase.TraceWriteLine($"Processing file: {file}");
if (MatchCsvValue(file, matchStr, readRowIndex, readColIndex))
{
string destFile = Path.Combine(targetDir, Path.GetFileName(file));
File.Move(file, destFile);
MyBase.TraceWriteLine($"Moved: {file} -> {destFile}");
//插入分发详情
CjlrTaskReleaseDetailModel detailModel = new CjlrTaskReleaseDetailModel
{
ModelsName = modelName, // 这里可以根据需要填写车型名称
ModelsCode = modelCode,
Position = position, // 这里可以根据需要填写位置
SourceFile = file,
TargetFile = destFile,
TaskFileName = Path.GetFileName(file),
TaskStatus = 1, // 假设1表示已处理
TaskDetail = "文件移动成功",
CreateDate = DateTime.Now
};
_dal.InsertTaskDetail(detailModel);
}
else
{
MyBase.TraceWriteLine($"No match for file: {file}");
//记录到数据库
CjlrTaskReleaseDetailModel detailModel = new CjlrTaskReleaseDetailModel
{
ModelsName = modelName, // 这里可以根据需要填写车型名称
ModelsCode = modelCode,
Position = position, // 这里可以根据需要填写位置
SourceFile = file,
TargetFile = "",
TaskFileName = Path.GetFileName(file),
TaskStatus = 2, // 假设2表示未处理
TaskDetail = "文件未匹配",
CreateDate = DateTime.Now
};
try
{
_dal.InsertTaskDetail(detailModel);
}
catch (Exception ex)
{
MyBase.TraceWriteLine($"记录错误到数据库失败: {ex.Message}");
}
}
}
}
/// <summary>
/// 检查CSV文件中指定行列的字符串是否匹配目标值
/// </summary>
/// <param name="filePath">CSV文件路径</param>
/// <param name="targetValue">要匹配的目标字符串</param>
/// <param name="rowIndex">行索引(从0开始)</param>
/// <param name="colIndex">列索引(从0开始)</param>
/// <returns>匹配成功返回true,否则false</returns>
public static bool MatchCsvValue(string filePath, string targetValue, int rowIndex, int colIndex)
{
try
{
string[] lines = File.ReadAllLines(filePath);
// 检查行索引是否有效
if (rowIndex < 0 || rowIndex >= lines.Length)
return false;
string[] columns = lines[rowIndex].Split(',');
// 检查列索引是否有效
if (colIndex < 0 || colIndex >= columns.Length)
return false;
return columns[colIndex].Trim().Equals(targetValue);
}
catch (Exception ex)
{
MyBase.TraceWriteLine($"处理CSV文件时出错: {ex.Message}");
return false;
}
}
public void test()
{
SQLHelper.connStr = DatabaseDfn.SqlConnectStr();
//string testPath = @"D:\CJLR\DATA\Input\LLL\K0902906.csv";
//bool result = MatchCsvValue(testPath, "X540_L", 3, 1);
//MyBase.TraceWriteLine($"匹配结果: {result}");
}
// 编写一个打印 DataTable 对象的方法,输入是对象
public static void PrintDataTable(DataTable dt)
{
if (dt == null || dt.Rows.Count == 0)
{
MyBase.TraceWriteLine("DataTable is empty or null.");
return;
}
foreach (DataColumn column in dt.Columns)
{
Console.Write($"{column.ColumnName}\t");
}
MyBase.TraceWriteLine("");
foreach (DataRow row in dt.Rows)
{
foreach (var item in row.ItemArray)
{
Console.Write($"{item}\t");
}
MyBase.TraceWriteLine("");
}
}
}
}