图片测试,csv文件日志,文件复制半成品
This commit is contained in:
1 parent
d9a3f19678
commit
57299c0b55
13 files changed
+1064
-85
No files matched your search
@@ -0,0 +1,85 @@
|
||||
using CsvHelper;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
|
||||
namespace WindowsFormsApp1
|
||||
{
|
||||
// 定义日志条目类
|
||||
public class LogEntry
|
||||
{
|
||||
public DateTime Timestamp { get; set; }
|
||||
public string Level { get; set; }
|
||||
public string Message { get; set; }
|
||||
public string Exception { get; set; }
|
||||
}
|
||||
|
||||
// 封装 CsvHelper 的日志记录类,设为静态类
|
||||
public static class CsvLogger
|
||||
{
|
||||
private static string _baseFilePath;
|
||||
private static List<string> _customHeaders = new List<string>();
|
||||
|
||||
public static void Initialize(string baseFilePath)
|
||||
{
|
||||
_baseFilePath = baseFilePath;
|
||||
}
|
||||
|
||||
// 设置自定义表头
|
||||
public static void SetHeaders(List<string> headers)
|
||||
{
|
||||
_customHeaders = headers;
|
||||
}
|
||||
|
||||
private static string GetCurrentLogFilePath()
|
||||
{
|
||||
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))
|
||||
{
|
||||
using (var writer = new StreamWriter(filePath))
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
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))
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
var fields = csvFormattedString.Split(',');
|
||||
foreach (var field in fields)
|
||||
{
|
||||
csv.WriteField(field);
|
||||
}
|
||||
csv.NextRecord();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user