本教程详细介绍如何使用 C# 语言编写代码,实现从本地 TXT 文件中读取文本内容,并将其显示在 Windows 窗体应用程序中的 TextBox 控件内的步骤和方法。
在C#中读取txt文本段落件并在TextBox中显示的方法如下:
1. 使用`StreamReader`类来打开并读取TXT文件。
2. 创建一个新实例的`StreamReader`,传入要读取的文件路径作为参数。
3. 通过循环逐行读取内容,并将每一行添加到字符串变量或直接更新TextBox控件的内容中。
4. 完成后关闭`StreamReader`对象以释放资源。
示例代码:
```csharp
using System.IO;
private void ReadFileAndShow()
{
string filePath = @C:\path\to\yourfile.txt; // 替换为实际文件路径
if (System.IO.File.Exists(filePath))
{
using (StreamReader sr = new StreamReader(File.OpenRead(filePath)))
{
string line;
while ((line = sr.ReadLine()) != null)
{
textBox1.AppendText(line + Environment.NewLine); // 将读取的每一行添加到TextBox中
}
}
}
}
```
确保在使用`StreamReader`时已正确处理异常,并且文件路径是正确的。