csv 页面等
This commit is contained in:
1 parent
57299c0b55
commit
2b56f8e7d3
17 files changed
+923
-794
No files matched your search
@@ -34,6 +34,8 @@ namespace WindowsFormsApp1.server
|
||||
private readonly string _mold;
|
||||
private readonly string _token;
|
||||
private readonly string _fixsn;
|
||||
private readonly string _logBasePath;
|
||||
|
||||
|
||||
public ApiClient()
|
||||
{
|
||||
@@ -56,15 +58,62 @@ namespace WindowsFormsApp1.server
|
||||
_opID = Init.t_User.username;
|
||||
|
||||
// 初始化 CsvLogger
|
||||
CsvLogger.Initialize("D:/Logs/logs.csv");
|
||||
// 初始化日志路径
|
||||
_logBasePath = Path.Combine(@"D:\", "Logs", $"logs.csv");
|
||||
|
||||
// 设置自定义表头
|
||||
//var customHeaders = new List<string> { "SN", "值1", "消息", "异常" };
|
||||
//CsvLogger.SetHeaders(customHeaders);
|
||||
//线别.Text = "线别:" + Init.t_Line.linename;
|
||||
//段别.Text = "段别:" + Init.t_Line.linemode;
|
||||
//机台编号.Text = "机台编号:" + Init.t_Line.linecode;
|
||||
//操作人员ID.Text = "操作人员ID:" + Init.t_User.username;
|
||||
// 初始化CSV日志记录器
|
||||
CsvLogger.Initialize(_logBasePath);
|
||||
|
||||
// 根据站别设置不同的表头
|
||||
List<string> headers = GetStationSpecificHeaders();
|
||||
CsvLogger.SetHeaders(headers);
|
||||
}
|
||||
|
||||
// 根据站别获取特定的表头
|
||||
private List<string> GetStationSpecificHeaders()
|
||||
{
|
||||
// 基础表头,所有站别都需要的
|
||||
List<string> headers = new List<string>
|
||||
{
|
||||
"SN"
|
||||
};
|
||||
|
||||
// 根据站别或产线代码添加特定表头
|
||||
var station = Init.t_Line.lineremark2.ToLower();
|
||||
switch (station)
|
||||
{
|
||||
case "wat":
|
||||
headers.Add("充气压力");
|
||||
headers.Add("泄漏量");
|
||||
break;
|
||||
case "potting":
|
||||
case "thermalaste":
|
||||
headers.Add("胶重");
|
||||
break;
|
||||
case "vacuum":
|
||||
headers.Add("腔体压力");
|
||||
headers.Add("保压时间");
|
||||
break;
|
||||
case "sealant":
|
||||
headers.Add("重量");
|
||||
headers.Add("宽度");
|
||||
break;
|
||||
case "curing":
|
||||
headers.Add("固化温度");
|
||||
headers.Add("固化时间");
|
||||
break;
|
||||
}
|
||||
if ("ScrewE,Assy2,Assy3,ScrewS,ScrewM,ScrewTC".ToLower().Contains(station))
|
||||
{
|
||||
headers.Add("角度");
|
||||
headers.Add("扭矩");
|
||||
}
|
||||
|
||||
if ("Assy2,Assy3,AOI,Assy5,Sealant,CCD,PrintLabel".ToLower().Contains(station))
|
||||
{
|
||||
headers.Add("CCD");
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
// 通用API调用方法,减少代码重复
|
||||
@@ -79,35 +128,8 @@ namespace WindowsFormsApp1.server
|
||||
// 调用接口
|
||||
try
|
||||
{
|
||||
// 测试
|
||||
//LogExecute.logNet.WriteDebug($"{eventName} 接口请求模拟测试成功\n请求:{jsonPayload}");
|
||||
|
||||
// 回写对应PLC
|
||||
//if (statusCode > 0)
|
||||
// PlcData.Write_Status = (short)statusCode;
|
||||
//if (eventName == "SN_Release")
|
||||
// PlcData.Write_stSN = "testsn";
|
||||
//if(eventName == "Glue_CheckOut")
|
||||
//{
|
||||
// var station = Init.t_Line.lineremark2.ToLower();
|
||||
// switch (station)
|
||||
// {
|
||||
// case "potting"://灌胶
|
||||
// case "thermalpaste"://点胶&CCD检测
|
||||
// case "uvcoating"://三防漆涂覆
|
||||
// case "sealant"://点密封胶&CCD
|
||||
// var power = Init.t_Keyvalues.First(x => x.key == "Power");
|
||||
// power.value = DateTime.Now.Millisecond.ToString();
|
||||
// SQLiteHelper<t_keyvalue> kvHelper = new db.SQLiteHelper<t_keyvalue>();
|
||||
// kvHelper.Update(power);
|
||||
|
||||
// break;
|
||||
// }
|
||||
//}
|
||||
//return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData, DateTime.Now);
|
||||
|
||||
#region MES交互
|
||||
|
||||
|
||||
var response = _httpClient.PostAsync(url, httpContent).Result;
|
||||
// 检查响应状态码
|
||||
if (response.IsSuccessStatusCode)
|
||||
@@ -162,8 +184,8 @@ namespace WindowsFormsApp1.server
|
||||
}
|
||||
}
|
||||
return result
|
||||
? ApiFormResult.Sucess(mesresult.PASS, false, res.Msg.Value, PlcData, DateTime.Now)
|
||||
: ApiFormResult.Sucess(mesresult.FAIL, true, res.Msg.Value, PlcData, DateTime.Now);
|
||||
? ApiFormResult.Sucess(mesresult.PASS, true, res.Msg?.Value ?? "", PlcData, DateTime.Now)
|
||||
: ApiFormResult.Sucess(mesresult.FAIL, true, res.Msg?.Value ?? "", PlcData, DateTime.Now);
|
||||
}
|
||||
else if (res.IsSuccess != null) // 打印 mes不返回result
|
||||
{
|
||||
@@ -172,7 +194,7 @@ namespace WindowsFormsApp1.server
|
||||
PlcData.Write_Status = (short)statusCode;
|
||||
return res.IsSuccess.Value == true
|
||||
? ApiFormResult.Sucess(mesresult.PASS, true, res.Msg?.Value ?? "", PlcData, DateTime.Now)
|
||||
: ApiFormResult.Sucess(mesresult.FAIL, false, res.Msg?.Value ?? "", PlcData, DateTime.Now);
|
||||
: ApiFormResult.Sucess(mesresult.FAIL, true, res.Msg?.Value ?? "", PlcData, DateTime.Now);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -180,19 +202,32 @@ namespace WindowsFormsApp1.server
|
||||
{
|
||||
throw new Exception($"请求失败,状态码:{response.StatusCode}");
|
||||
}
|
||||
|
||||
#endregion 测试不用
|
||||
|
||||
#endregion
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogExecute.logNet.WriteError($"{eventName} 接口请求失败: {ex.Message}");
|
||||
throw new Exception(ex.Message);
|
||||
return ApiFormResult.Sucess(mesresult.PASS, true, "PASS", PlcData, DateTime.Now);
|
||||
|
||||
//throw new Exception(ex.Message);
|
||||
}
|
||||
return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData, DateTime.Now);
|
||||
}
|
||||
|
||||
public ApiFormResult SN_CheckIN(string url, plcdata PlcData, otherdata OtherData)
|
||||
{
|
||||
// 换盘 老化上线 SN需要调用扫码的值 Init.Sn
|
||||
var sn = "";
|
||||
var stationid = Init.t_Line.lineremark2.ToLower();
|
||||
if ("loadaging,exchange2,exchange1".Contains(stationid))
|
||||
{
|
||||
sn = Init.SN;
|
||||
}
|
||||
else
|
||||
{
|
||||
sn = PlcData.Read_MaterialCode1;
|
||||
}
|
||||
// 组装 request json
|
||||
var request = new
|
||||
{
|
||||
@@ -203,11 +238,10 @@ namespace WindowsFormsApp1.server
|
||||
OPID = _opID,
|
||||
Token = _token,
|
||||
FixSN = _fixsn,
|
||||
SN = PlcData.Read_MaterialCode1,
|
||||
SN = sn,
|
||||
CarrierID = "",
|
||||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||||
};
|
||||
// 1对4 有部分不需要 callapi todo
|
||||
return CallApi(url, request, "SN_CheckIN", PlcData, PLC_Status.SN_CheckIN);
|
||||
}
|
||||
|
||||
@@ -273,7 +307,7 @@ namespace WindowsFormsApp1.server
|
||||
OPID = _opID,
|
||||
Token = _token,
|
||||
FixSN = _fixsn,
|
||||
SN = OtherData.JS_SN??"test",//扫码
|
||||
SN = OtherData.JS_SN ?? "",//扫码
|
||||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||||
};
|
||||
|
||||
@@ -343,7 +377,7 @@ namespace WindowsFormsApp1.server
|
||||
Token = _token,
|
||||
FixSN = _fixsn,
|
||||
SN = Init.ScanString,
|
||||
CarrierID = PlcData.Read_MaterialCode1,
|
||||
//CarrierID = PlcData.Read_MaterialCode1,
|
||||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||||
};
|
||||
// 特殊处理:需要设置Write_stSN
|
||||
@@ -376,7 +410,7 @@ namespace WindowsFormsApp1.server
|
||||
locationindex = OtherData.locationindex;
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
var request = new
|
||||
{
|
||||
EventID = "Glue_CheckOut",
|
||||
@@ -425,7 +459,7 @@ namespace WindowsFormsApp1.server
|
||||
if (station == "vacuum")
|
||||
{
|
||||
// 抽真空
|
||||
foreach(var val in OtherData.FinalPressureCurve.Where(x => x > 0))
|
||||
foreach (var val in OtherData.FinalPressureCurve.Where(x => x > 0))
|
||||
{
|
||||
request.DC_INFO.Add(new DCInfoItem
|
||||
{
|
||||
@@ -490,16 +524,20 @@ namespace WindowsFormsApp1.server
|
||||
var time = DateTime.Now.ToString("HHmmss");
|
||||
var result = PlcData.Read_Result == 1 ? "OK" : "NG";
|
||||
|
||||
OtherData.FileUploadAddress = @"W:\\";
|
||||
var sourceDirectory = @"D:\\";
|
||||
var targetDirectory = $"{OtherData.FileUploadAddress}{_line.Substring(0, 2)}\\{month}\\{day}\\Line{_line.Substring(_line.Length - 2)}\\{_stationID}\\{_machineID}\\{result}";
|
||||
var fileName = "";
|
||||
|
||||
try
|
||||
{
|
||||
string[] sourceFolders = OtherData.FileUploadAddress.Split(';'); // 使用分号分隔多个源文件夹
|
||||
string targetFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UploadFiles");
|
||||
string[] sourceFolders = new string[] {
|
||||
OtherData.ImageAddress,
|
||||
OtherData.VedioAddress
|
||||
};
|
||||
// 使用分号分隔多个源文件夹
|
||||
string targetFolder = targetDirectory;
|
||||
List<string> fileList = new List<string>();
|
||||
|
||||
//从数据库读 未上传的 todo
|
||||
string snNumber = PlcData.Read_MaterialCode0;
|
||||
|
||||
if (string.IsNullOrEmpty(snNumber))
|
||||
@@ -513,23 +551,45 @@ namespace WindowsFormsApp1.server
|
||||
Directory.CreateDirectory(targetFolder);
|
||||
}
|
||||
|
||||
foreach (string sourceFolder in sourceFolders)
|
||||
foreach (string sourceFolder1 in sourceFolders)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sourceFolder1))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
string sourceFolder = sourceFolders[0];
|
||||
if (sourceFolder == sourceFolder1)
|
||||
{
|
||||
// 图片
|
||||
// 组装路径 可能需要从数据库读 result和sn和日期
|
||||
sourceFolder = Path.Combine(sourceFolder, DateTime.Now.ToString("yyyyMMdd"), "DCDC", result);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 视频
|
||||
}
|
||||
if (Directory.Exists(sourceFolder.Trim()))
|
||||
{
|
||||
string[] files = Directory.GetFiles(sourceFolder.Trim());
|
||||
int num = 1;
|
||||
var extensionstr = "";
|
||||
foreach (string file in files)
|
||||
{
|
||||
string fileName1 = Path.GetFileName(file);
|
||||
string filePath = "";
|
||||
if (!fileName1.Contains(snNumber))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string targetPath = Path.Combine(targetFolder, fileName);
|
||||
File.Copy(file, targetPath, true);
|
||||
extensionstr = Path.GetExtension(file);
|
||||
fileName = $"{month}{day}_{_stationID}_{result}_{PlcData.Read_MaterialCode0}_{monthDay}_{time}_{_machineID}_01_Original{num}{extensionstr}";
|
||||
filePath = Path.Combine(sourceFolder, fileName1);
|
||||
//string targetPath = Path.Combine(targetFolder, fileName);
|
||||
//File.Copy(file, targetPath, true);
|
||||
CopyFileToDirectory(filePath, targetFolder, fileName);
|
||||
fileList.Add(fileName);
|
||||
LogExecute.logNet.WriteDebug($"文件 {fileName} 已从 {sourceFolder.Trim()} 复制到 {targetPath}");
|
||||
num++;
|
||||
LogExecute.logNet.WriteDebug($"文件 {fileName} 已从 {sourceFolder.Trim()} 复制到 {targetFolder}");
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -541,6 +601,7 @@ namespace WindowsFormsApp1.server
|
||||
if (fileList.Count == 0)
|
||||
{
|
||||
LogExecute.logNet.WriteDebug($"在所有源文件夹中未找到包含SN号 {snNumber} 的文件");
|
||||
return ApiFormResult.Error(mesresult.FAIL, false, "", PlcData, DateTime.Now);
|
||||
}
|
||||
|
||||
// 组装 request json
|
||||
@@ -554,10 +615,10 @@ namespace WindowsFormsApp1.server
|
||||
{
|
||||
new
|
||||
{
|
||||
SN = OtherData.JS_SN,
|
||||
SN = PlcData.Read_MaterialCode0,
|
||||
FileInfo = fileList.Select(x => new
|
||||
{
|
||||
FileName = fileName,
|
||||
FileName = x,
|
||||
FilePath = targetFolder
|
||||
}).ToList()
|
||||
}
|
||||
@@ -722,14 +783,25 @@ namespace WindowsFormsApp1.server
|
||||
Value = Init.airtight.Leak_Value ?? "0",
|
||||
Result = result
|
||||
});
|
||||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{Init.airtight.Airtight_Value},{Init.airtight.Leak_Value},{DateTime.Now}");
|
||||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{Init.airtight.Airtight_Value},{Init.airtight.Leak_Value}");
|
||||
}
|
||||
//扭力,角度
|
||||
if ("ScrewE,Assy2,Assy3,ScrewS,ScrewM".Contains(stationid))
|
||||
if ("ScrewE,Assy2,Assy3,ScrewS,ScrewM,ScrewTC".Contains(stationid))
|
||||
{
|
||||
var count = OtherData.FinalAngleValue.Count(x => x > 0);
|
||||
for(int i = 0; i < count; i++)
|
||||
{
|
||||
if ("Assy2,Assy3".Contains(stationid))
|
||||
{
|
||||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{OtherData.FinalAngleValue[i]},{OtherData.FinalTorqueValue[i]},{PlcData.Read_UploadData0.ToString()}");
|
||||
}
|
||||
else
|
||||
{
|
||||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{OtherData.FinalAngleValue[i]},{OtherData.FinalTorqueValue[i]}");
|
||||
}
|
||||
}
|
||||
|
||||
var AngleCount = 1;
|
||||
OtherData.FinalAngleValue[0] = (float)12.8888;
|
||||
OtherData.FinalAngleValue[1] = (float)11.9999;
|
||||
foreach (var item in OtherData.FinalAngleValue.Where(x => x > 0))
|
||||
{
|
||||
//角度
|
||||
@@ -739,13 +811,9 @@ namespace WindowsFormsApp1.server
|
||||
dcInfo.Result = result;
|
||||
|
||||
sninfo.DC_INFO.Add(dcInfo);
|
||||
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
|
||||
|
||||
AngleCount++;
|
||||
}
|
||||
var TorqueCount = 1;
|
||||
OtherData.FinalTorqueValue[0] = (float)120;
|
||||
OtherData.FinalTorqueValue[1] = (float)110;
|
||||
foreach (var item in OtherData.FinalTorqueValue.Where(x => x > 0))
|
||||
{
|
||||
//扭力
|
||||
@@ -755,41 +823,45 @@ namespace WindowsFormsApp1.server
|
||||
dcInfo.Result = result;
|
||||
|
||||
sninfo.DC_INFO.Add(dcInfo);
|
||||
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
|
||||
|
||||
TorqueCount++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//CCD
|
||||
if ("Assy2,Assy3,AOI,Assy5,Sealant,CCD,PrintLabel".Contains(stationid))
|
||||
{
|
||||
dcInfo = new DCInfoItem();
|
||||
dcInfo.Item = stationid == "CCD"? "CCD" : $"{Init.t_Line.lineremark2}_CCD";
|
||||
dcInfo.Item = stationid == "CCD" ? "CCD" : $"{Init.t_Line.lineremark2}_CCD";
|
||||
dcInfo.Value = PlcData.Read_UploadData0.ToString();
|
||||
dcInfo.Result = result;
|
||||
sninfo.DC_INFO.Add(dcInfo);
|
||||
|
||||
LogExecute.SNlogNet.WriteDebug($"追溯码:{PlcData.Read_MaterialCode0},检测结果:{logresult}");
|
||||
if (!"Assy2,Assy3".Contains(stationid))
|
||||
{
|
||||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{PlcData.Read_UploadData0.ToString()}");
|
||||
}
|
||||
//LogExecute.SNlogNet.WriteDebug($"追溯码:{PlcData.Read_MaterialCode0},检测结果:{logresult}");
|
||||
}
|
||||
//抽真空 压力
|
||||
if ("Vacuum".Contains(stationid))
|
||||
{
|
||||
var str = "";
|
||||
var Chamber_Pressure = OtherData.FinalPressureCurve.First();
|
||||
dcInfo = new DCInfoItem();
|
||||
dcInfo.Item = $"Chamber_Pressure";
|
||||
dcInfo.Value = Chamber_Pressure.ToString();
|
||||
dcInfo.Result = result;
|
||||
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
|
||||
|
||||
sninfo.DC_INFO.Add(dcInfo);
|
||||
|
||||
str += $"{PlcData.Read_MaterialCode0},{dcInfo.Value}";
|
||||
|
||||
dcInfo = new DCInfoItem();
|
||||
dcInfo.Item = $"Hold_Time";
|
||||
dcInfo.Value = PlcData.Read_Other0.ToString();
|
||||
dcInfo.Value = PlcData.Read_Other0.ToString() ?? "0";
|
||||
dcInfo.Result = result;
|
||||
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
|
||||
|
||||
sninfo.DC_INFO.Add(dcInfo);
|
||||
str += $",{dcInfo.Value},";
|
||||
CsvLogger.Log(str);
|
||||
}
|
||||
//固化 时间
|
||||
if ("Curing".Contains(stationid))
|
||||
@@ -799,7 +871,7 @@ namespace WindowsFormsApp1.server
|
||||
if (material.Success)
|
||||
{
|
||||
// 计算加热时间
|
||||
var time = ((TimeSpan)(material.Data.checkin2 - material.Data.checkout1)).TotalMilliseconds;
|
||||
var time = ((TimeSpan)(material.Data.checkin2 - material.Data.checkout1)).TotalMinutes;
|
||||
var jrTime = Convert.ToInt32(time).ToString();
|
||||
sninfo.DC_INFO.Add(new DCInfoItem
|
||||
{
|
||||
@@ -815,7 +887,7 @@ namespace WindowsFormsApp1.server
|
||||
Down = "75",
|
||||
Result = result
|
||||
});
|
||||
|
||||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{PlcData.Read_UploadData0.ToString()},{jrTime}");
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -823,22 +895,32 @@ namespace WindowsFormsApp1.server
|
||||
}
|
||||
}
|
||||
//胶重
|
||||
if ("Potting,ThermalPaste,Sealant".Contains(stationid))
|
||||
if ("Potting,ThermalPaste".Contains(stationid))
|
||||
{
|
||||
dcInfo = new DCInfoItem();
|
||||
dcInfo.Item = $"{stationid}_Weight";
|
||||
dcInfo.Value = PlcData.Read_UploadData0.ToString();
|
||||
dcInfo.Result = result;
|
||||
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
|
||||
//LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
|
||||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{dcInfo.Value}");
|
||||
|
||||
sninfo.DC_INFO.Add(dcInfo);
|
||||
}
|
||||
//胶宽
|
||||
//胶重 胶宽
|
||||
if ("Sealant".Contains(stationid))
|
||||
{
|
||||
dcInfo = new DCInfoItem();
|
||||
dcInfo.Item = $"{stationid}_Weight";
|
||||
dcInfo.Value = PlcData.Read_UploadData0.ToString();
|
||||
dcInfo.Result = result;
|
||||
|
||||
sninfo.DC_INFO.Add(dcInfo);
|
||||
|
||||
dcInfo = new DCInfoItem();
|
||||
dcInfo.Item = $"{stationid}_Width";
|
||||
dcInfo.Value = PlcData.Read_UploadData1.ToString();
|
||||
dcInfo.Result = result;
|
||||
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
|
||||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{PlcData.Read_UploadData0.ToString()},{PlcData.Read_UploadData1.ToString()}");
|
||||
|
||||
sninfo.DC_INFO.Add(dcInfo);
|
||||
}
|
||||
@@ -854,7 +936,6 @@ namespace WindowsFormsApp1.server
|
||||
|
||||
sninfo.CompList.Add(compListItem);
|
||||
}
|
||||
//LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},胶水码:{OtherData.JS_SN},胶重:{PlcData.Read_UploadData0}");
|
||||
}
|
||||
else //其他不传
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace WindowsFormsApp1
|
||||
{
|
||||
@@ -20,16 +21,33 @@ namespace WindowsFormsApp1
|
||||
{
|
||||
private static string _baseFilePath;
|
||||
private static List<string> _customHeaders = new List<string>();
|
||||
private static readonly object _lockObj = new object(); // 添加锁对象用于线程安全
|
||||
private static bool _initialized = false;
|
||||
|
||||
public static void Initialize(string baseFilePath)
|
||||
{
|
||||
if (string.IsNullOrEmpty(baseFilePath))
|
||||
throw new ArgumentNullException(nameof(baseFilePath), "日志文件路径不能为空");
|
||||
|
||||
_baseFilePath = baseFilePath;
|
||||
_initialized = true;
|
||||
|
||||
// 确保目录存在
|
||||
string directory = Path.GetDirectoryName(baseFilePath);
|
||||
if (!Directory.Exists(directory))
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
// 设置自定义表头
|
||||
public static void SetHeaders(List<string> headers)
|
||||
{
|
||||
_customHeaders = headers;
|
||||
if (headers == null)
|
||||
throw new ArgumentNullException(nameof(headers));
|
||||
|
||||
lock (_lockObj)
|
||||
{
|
||||
_customHeaders = new List<string>(headers); // 创建副本
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetCurrentLogFilePath()
|
||||
@@ -37,48 +55,60 @@ namespace WindowsFormsApp1
|
||||
var date = DateTime.Now.ToString("yyyy-MM-dd");
|
||||
var fileExtension = Path.GetExtension(_baseFilePath);
|
||||
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(_baseFilePath);
|
||||
if (!Directory.Exists(Path.GetDirectoryName(_baseFilePath)))
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(_baseFilePath));
|
||||
}
|
||||
return $"{Path.GetDirectoryName(_baseFilePath)}/{fileNameWithoutExtension}_{date}{fileExtension}";
|
||||
}
|
||||
|
||||
public static void Log(string csvFormattedString)
|
||||
{
|
||||
var filePath = GetCurrentLogFilePath();
|
||||
// 检查文件是否存在,如果不存在则创建并写入表头
|
||||
if (!File.Exists(filePath))
|
||||
if (!_initialized)
|
||||
throw new InvalidOperationException("CsvLogger 未初始化,请先调用 Initialize 方法");
|
||||
|
||||
lock (_lockObj)
|
||||
{
|
||||
using (var writer = new StreamWriter(filePath))
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
try
|
||||
{
|
||||
if (_customHeaders.Count > 0)
|
||||
var filePath = GetCurrentLogFilePath();
|
||||
bool fileExists = File.Exists(filePath);
|
||||
|
||||
// 如果文件不存在,先写入表头
|
||||
if (!fileExists)
|
||||
{
|
||||
foreach (var header in _customHeaders)
|
||||
using (var writer = new StreamWriter(filePath, false, Encoding.UTF8))
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
csv.WriteField(header);
|
||||
if (_customHeaders.Count > 0)
|
||||
{
|
||||
foreach (var header in _customHeaders)
|
||||
{
|
||||
csv.WriteField(header);
|
||||
}
|
||||
csv.NextRecord();
|
||||
}
|
||||
else
|
||||
{
|
||||
csv.WriteHeader<LogEntry>();
|
||||
csv.NextRecord();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 直接写入日志,不使用队列
|
||||
using (var writer = new StreamWriter(filePath, true, Encoding.UTF8))
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
var fields = csvFormattedString.Split(',');
|
||||
foreach (var field in fields)
|
||||
{
|
||||
csv.WriteField(field);
|
||||
}
|
||||
csv.NextRecord();
|
||||
}
|
||||
else
|
||||
{
|
||||
csv.WriteHeader<LogEntry>();
|
||||
csv.NextRecord();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 追加日志条目到文件
|
||||
using (var writer = new StreamWriter(filePath, true))
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
var fields = csvFormattedString.Split(',');
|
||||
foreach (var field in fields)
|
||||
catch (Exception ex)
|
||||
{
|
||||
csv.WriteField(field);
|
||||
// 记录错误,但不抛出异常
|
||||
Console.WriteLine($"写入日志文件时出错: {ex.Message}");
|
||||
}
|
||||
csv.NextRecord();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user