在页面上放2个button和一个文本框。引用命名空间 System.IO
protected void Button1_Click(object sender, EventArgs e)
{
if (GridView1.Rows.Count == 0)
{
Response.Write("");
}
else
{
string s1 = GridView1.Rows[0].Cells[1].Text;
string s2 = GridView1.Rows[0].Cells[2].Text;
FileStream fs = new FileStream("c:\\aaa.txt",FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(s1);
sw.WriteLine(s2);
sw.Close();
fs.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
string s;
if (File.Exists("c:\\aaa.txt"))
{
FileStream fs = new FileStream("c:\\aaa.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs);
s = sr.ReadToEnd();
sr.Close();
fs.Close();
}
else
{
s = "文件不存在";
}
this.TextBox1.Text = s;
}
Button1_Click是写文件的过程。
Button2_Click是读文件的过程。
把代码放到对应的事件中就行了。
private void button1_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("c:\\123.txt", Encoding.GetEncoding("GB2312"));
String line;
//while ((line = sr.ReadLine()) != null)
//{
// textBox1 .Text +=line.ToString()+"\r\n";
//}
line = sr.ReadLine();
dataGridView1.Rows[0].Cells[0].Value= line.ToString() + "\r\n";
}