C#开发一个window窗口程序,从文件中读取所有内容并在界面中显示出来,并显示出统计读取的字节总数
时间: 2024-03-15 21:44:50 浏览: 21
好的,以下是实现的代码:
```csharp
using System;
using System.IO;
using System.Windows.Forms;
namespace ReadFileApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// 打开文件对话框,选择要打开的文件
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
// 读取文件中的所有内容
string content = File.ReadAllText(openFileDialog.FileName);
// 将读取的内容显示在界面的文本框中
textBox1.Text = content;
// 统计读取的字节总数
int byteCount = Encoding.Default.GetByteCount(content);
label1.Text = "总字节数:" + byteCount;
}
catch (Exception ex)
{
MessageBox.Show("读取文件出错:" + ex.Message);
}
}
}
}
}
```
在窗口中添加一个文本框和一个标签,用于显示文件内容和字节总数。在窗口中添加一个按钮,点击按钮后弹出文件对话框,选择要打开的文件,然后读取文件中的所有内容并显示在文本框中,同时统计读取的字节总数并显示在标签中。