日期:2014-05-18  浏览次数:20704 次

C#浏览选择,读写TXT问题,请进
需求如下,有一个浏览按钮,可以选择我要读写哪个TXT文件(只能限定为TXT),然后把TXT里面的内容展现在textbox1中。还有个按钮,是写入功能的,把textbox2写入到这个TXT文件中。表达不是很清楚,不过应该知道大概意思了吧。。。请教高手

------解决方案--------------------
你可以将修改后的内容保存一下吧
 private void button_Click(object sender, EventArgs e)
{
if (File.Exists(filename))
{
richTextBox1.SaveFile(filename, RichTextBoxStreamType.RichText);
MessageBox.Show("保存成功", "提示信息");
richTextBox1.Clear();
}
else
{
SaveFileDialog saveFileDilog1 = new SaveFileDialog();
saveFileDilog1.Filter="*.rtf";
if (saveFileDilog1.ShowDialog()==DialogResult.OK && saveFileDilog1.FileName.Length > 0)
{
richTextBox1.SaveFile(saveFileDilog1.FileName+".rtf");
}
}
}
------解决方案--------------------
声明一个全局变量存放TXT文本所在的路径。
你是用openFileDialog打开文件的吧。
简单的写一下,你自己参考下吧。
C# code

      public partial class Form1 : Form
      {
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 全局变量,用来存放TXT路径
        /// </summary>
        private string txtPath = String.Empty;

        /// <summary>
        /// 打开文本文档
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Opne_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();

            //得到文本路径,显示出来
            txtPath = openFileDialog1.FileName;

            if (txtPath == "") return;
            StreamReader sr = new StreamReader(txtPath, System.Text.Encoding.Default);
            string strText = sr.ReadToEnd();
            sr.Close();
            sr.Dispose();
            textBox1.Text = strText;
        }

        /// <summary>
        /// 保存文本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Save_Click(object sender, EventArgs e)
        {
            WriteTxt(textBox1.Text, txtPath);
        }


        /// <summary>
        /// 写入
        /// </summary>
        /// <param name="strMemo">写入的字符串</param>
        /// <param name="path">文本所在的路径</param>
        public void WriteTxt(string strMemo, string path)
        {
            StreamWriter sw = new StreamWriter(path, true);
            sw.WriteLine(strMemo);
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
    }