StreamWriter、StreamReader
阅读原文时间:2023年07月15日阅读:1

IO流操作文件内容,using System.IO;//引入命名空间

    private void button1\_Click(object sender, EventArgs e)  
    {  
        if (textBox1.Text==string.Empty)  
        {  
            MessageBox.Show("写入内容不能为空");  
        }  
        else  
        {  
            saveFileDialog1.Filter = "文本文件(\*.txt)|\*.txt";//打开保存文件对话框  
            if (saveFileDialog1.ShowDialog()==DialogResult.OK)//单机OK按钮  
            {  
                StreamWriter sw = new StreamWriter(saveFileDialog1.FileName, true);//创建写入流  
                sw.WriteLine(textBox1.Text);//写入  
                sw.Close();//关闭流  
            }  
        }  
    }  
    private void button2\_Click(object sender, EventArgs e)  
    {  
        openFileDialog1.Filter = "文本文件(\*.txt)|\*.txt";  
        if (openFileDialog1.ShowDialog()==DialogResult.OK)  
        {  
            StreamReader sr = new StreamReader(openFileDialog1.FileName);//创建读出流  
            textBox1.Text = sr.ReadToEnd();//读出全部内容  
            sr.Close();//关闭流  
        }  
    }