文件操作3(編輯器例子)

file類方法

首先加入幾個控件,兩個分組空間,一個文本框,三個按鈕,一個richTextBox控件,用於寫入信息,佈局如下:
窗體佈局

下面是代碼:

 //保存文件路徑的全局變量
        private static string Depath = "";

首先創建文件

  if (textBox1.Text.Length < 0)
            {
                MessageBox.Show("輸入文件信息");
            }
            else
            {

                Depath = @"" + textBox1.Text.Trim() + "";
                if (File.Exists(Depath)) MessageBox.Show("文本文件已存在,請重新命名");
                else
                {
                    StreamWriter sw = File.CreateText(Depath);
                    MessageBox.Show("文件已創建");
                    sw.Close();
                }
            }

保存文件信息

  Depath = textBox1.Text.Trim();
            FileStream file = File.Open(Depath,FileMode.OpenOrCreate,FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(file,Encoding.UTF8);
            sw.Write(richTextBox1.Text.ToString());
            MessageBox.Show("文件寫入成功");

            sw.Close();

打開文件編輯框,這裏用到OpenFileDialog,代碼如下:

 try
            {
                //打開文件對話框
                OpenFileDialog op = new OpenFileDialog();
                op.Title = "打開文本文件";
                op.FileName = "";
                op.AddExtension = true;//檢查文件擴展名
                op.CheckFileExists = true;//指定文件是否存在
                op.CheckPathExists = true;//檢測路徑合法性
                op.Filter = "文本文件(*.txt)|*.txt";
                op.ValidateNames = true;//接受有效的文件名
                //判斷是否點擊了確定按鈕
                if (op.ShowDialog() == DialogResult.OK) {
                    StreamReader sr = new StreamReader(op.FileName,Encoding.Default);
                    this.richTextBox1.Text = sr.ReadToEnd();
                   textBox1.Text  = op.FileName;

                    sr.Close();
               }
                MessageBox.Show("文件打開成功");

            }
            catch (Exception e1)
            {

                MessageBox.Show("錯誤"+e1.ToString());
            }

好了,簡單的小示例基本完成,但要注意一點,每做完一個文件操作都必須把讀寫器關閉,否則會提示進程佔用;
**上述代碼還需注意一點,容易忘記;當打開文件時候,要把路徑變量賦值,即

 textBox1.Text  = op.FileName;
     Depath = textBox1.Text.Trim();

不然保存編輯的文本時 Depath是空值;**

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章