Files
6150-HMI/CowainHmi/Common/LogSearch.cs
2026-01-15 15:06:36 +08:00

134 lines
4.2 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace CowainHmi
{
public partial class LogSearch : UserControl
{
public LogSearch()
{
InitializeComponent();
dateTimePicker1.Value = DateTime.Now;
}
// 定义并添加自定义属性
[Browsable(true)]
[Category("Custom Properties")]
[Description("日志文件路径")]
public string LogFilePath
{
get;
set;
}
public class LogEntry
{
public DateTime { get; set; }
public string { get; set; }
public string { get; set; }
}
private void search_Click(object sender, EventArgs e)
{
List<LogEntry> list = new List<LogEntry>();
dataGridView1.DataSource = list;
// 读取并解析CSV文件
string logFolder = LogFilePath + @"\" + dateTimePicker1.Value.ToString("yyMMdd") + ".csv";
if (!File.Exists(logFolder))
{
MessageBox.Show("没有选择文件,或文件不存在!");
return;
}
var logEntries = ReadLogEntries(logFolder);
// 按时间段过滤日志条目
list = logEntries.Where(entry => entry..ToLower().Contains(content.Text.ToLower().Trim())).OrderByDescending(x=>x.).ToList();
dataGridView1.DataSource = list;
}
static List<LogEntry> ReadLogEntries(string filePath)
{
var logEntries = new List<LogEntry>();
int N = 1;
foreach (var line in File.ReadAllLines(filePath, Encoding.GetEncoding("GB2312")))
{
try
{
if (N == 1)
{
N++;
continue;
}
var parts = line.Split(',');
var time = DateTime.ParseExact(parts[0].Trim(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
string actionOperator= parts[1].Trim();
string content = "";
for (int i = 2; i < parts.Length; i++)
{
content = content +" "+ parts[i].Trim();
}
logEntries.Add(new LogEntry { = time,= actionOperator, = content });
}
catch (Exception ex)
{
//throw;
}
N++;
}
return logEntries;
}
public string ShowOpenFileDialog()
{
using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
{
folderBrowserDialog.Description = "请选择一个文件夹";
folderBrowserDialog.ShowNewFolderButton = true;
folderBrowserDialog.SelectedPath = AppDomain.CurrentDomain.BaseDirectory;
DialogResult result = folderBrowserDialog.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(folderBrowserDialog.SelectedPath))
{
return folderBrowserDialog.SelectedPath;
}
else
{
return "";
}
}
}
private void logFileSelect_Click(object sender, EventArgs e)
{
LogFilePath = ShowOpenFileDialog();
logFileSelect.Text = LogFilePath;
if (logFileSelect.Text.Length<3)
{
logFileSelect.Text = "点击选择日志文件";
}
}
private void LogSearch_Load(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(LogFilePath))
{
logFileSelect.Text = "点击选择日志文件";
}
else
{
logFileSelect.Text= LogFilePath;
}
}
}
}