LagerFileView/MainView.cs
2025-10-17 14:11:06 +08:00

87 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LagerFileView
{
public partial class MainView:Form
{
public string FilePath { get; set; }
public int LineNo { get; set; }
public int PageSize { get; set; } = 1000;
public CancellationTokenSource CancelSource { get; set; } = new CancellationTokenSource();
public MainView() {
InitializeComponent();
}
private void butOpenFile_Click(object sender,EventArgs e) {
this.CancelSource.Cancel();
using(var fileDlg = new OpenFileDialog()) {
fileDlg.Filter = "文本文件 (*.txt;*.log)|*.txt;*.log|所有文件 (*.*)|*.*";
if(fileDlg.ShowDialog() == DialogResult.OK) {
this.FilePath = fileDlg.FileName;
this.labStatus.Text = "找到文件,正在打开...";
this.CancelSource = new CancellationTokenSource();
OpenFileTask(this.CancelSource.Token);
}
}
}
private void OpenFileTask(CancellationToken cancellation) {
this.trbFileText.Clear();
Task.Factory.StartNew(() => {
using var fs = new FileStream(this.FilePath,FileMode.Open,FileAccess.Read);
using var reader = new StreamReader(fs);
string? line;
int cl = 0;
int start = this.PageSize * this.LineNo;
int end = start + this.PageSize;
while((line = reader.ReadLine()) != null) {
if(cancellation.IsCancellationRequested) {
break;
}
if(cl < start) {
cl++;
continue;
}
if(cl > end) {
break;
}
this.Invoke(() => {
this.trbFileText.AppendText(line + "\n");
});
cl++;
}
this.labStatus.Text = $"已打开第{start}行至{cl}行";
});
}
private void moveLast_Click(object sender,EventArgs e) {
this.LineNo--;
this.LineNo = Math.Max(0,this.LineNo);
this.CancelSource.Cancel();
this.CancelSource = new CancellationTokenSource();
OpenFileTask(this.CancelSource.Token);
}
private void moveNext_Click(object sender,EventArgs e) {
this.LineNo++;
this.CancelSource.Cancel();
this.CancelSource = new CancellationTokenSource();
OpenFileTask(this.CancelSource.Token);
}
}
}