首页 > 编程语言 >C#使用StreamReader类和StreamWriter类读写文本文件

C#使用StreamReader类和StreamWriter类读写文本文件

时间:2022-10-15 23:07:25浏览次数:40  
标签:StreamWriter MessageBox C# System using txt StreamReader


StreamReader类和StreamWriter类可以实现读写文本文件,这两个类都在命名空间System.IO下。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormStream
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnWriter_Click(object sender, EventArgs e)
{
using (StreamWriter streamWriter = new StreamWriter("test.txt"))
{
for (int i = 1; i <= 10; i++)
{
streamWriter.WriteLine(i + ":" + DateTime.Now.ToString() + " \r\n");
}
}
MessageBox.Show("文件写入成功!");
}

private void btnReader_Click(object sender, EventArgs e)
{
try
{
if (!File.Exists("test.txt"))
{
MessageBox.Show("test.txt文件不存在");
}
using (StreamReader streamReader = new StreamReader("test.txt"))
{
string line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = streamReader.ReadLine()) != null)
{
stringBuilder.Append(line);
}
MessageBox.Show(stringBuilder.ToString());
}
} catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

C#使用StreamReader类和StreamWriter类读写文本文件_文本文件


标签:StreamWriter,MessageBox,C#,System,using,txt,StreamReader
From: https://blog.51cto.com/lilongsy/5759357

相关文章