赞
踩
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);
}
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。