RT,我就只会写到这里,不知道如何操作,求指教!
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description = "请选择文件路径";
if (dialog.ShowDialog() == DialogResult.OK)
{
string savePath = dialog.SelectedPath.ToString();
textBox1.Text = savePath;
string str;
StreamReader sr = new StreamReader(@"C:\python测试\2.txt", false);
str = sr.ReadLine().ToString();
sr.Close();
textBox2.Text = str;
}
}
使用Directory.GetFiles()
方法获取指定目录中的所有txt文件,然后使用File.ReadAllLines()
方法读取指定文件的所有行,最后通过.Length
属性获取每个文件的行数。
运行效果如下:
示例代码:
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp1.Forms.Demo2
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var dialog = new FolderBrowserDialog();
dialog.Description = "请选择文件路径";
if (dialog.ShowDialog() == DialogResult.OK)
{
var savePath = dialog.SelectedPath;
textBox1.Text = savePath;
var result = Directory
.GetFiles(savePath, "*.txt", SearchOption.AllDirectories)
.Select(x => $"文件名:{x}, 行数:{File.ReadAllLines(x).Length}")
.ToList();
richTextBox1.Text = string.Join(Environment.NewLine, result);
}
}
}
}
读取文件,改用 File.ReadAllLLines()
.
手打代码:
var result = Directory
.GetFiles(savePath, "*.txt", SearchOption.AllDirectories)
.Select(x => $"{x.fileName},行数:{File.ReadAllLines(x).Length}")
.ToList();
var resultStr = string.join("\r\n", result);
File.WriteAllText("test.csv", resultStr,Encoding.Default);
这里解释一下就是csv文件,用excel能打开