C#寫入TXT文字檔

來源:互聯網
上載者:User

C#寫入TXT文字檔

//=====================
//描述:寫入TXT檔案
//返回:void
//作者:Kunsa
//建立時間:2010.5.4 8:25
//狀態:已完成
//修改:
//=====================private void TxtWrite(string strToWrite,string filename)
{
    FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
    StreamWriter sw = new StreamWriter(fs);
    sw.BaseStream.Seek(0, SeekOrigin.Begin);
    sw.WriteLine(strToWrite);
    sw.Close();
} ---------------------------------------------------------------------------------------------

      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)
                {
                    //使用“另存新檔”對話方塊中輸入的檔案名稱執行個體化StreamWriter對象
                    StreamWriter sw = new StreamWriter(saveFileDialog1.FileName, true);
                    //向建立的檔案中寫入內容
                    sw.WriteLine(textBox1.Text);
                    //關閉當前檔案寫入流
                    sw.Close();
                    textBox1.Text = string.Empty;
                }
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            //設定開啟檔案的格式
            openFileDialog1.Filter = "文字檔(*.txt)|*.txt";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = string.Empty;
                //使用“開啟”對話方塊中選擇的檔案執行個體化StreamReader對象
                StreamReader sr = new StreamReader(openFileDialog1.FileName);
                //調用ReadToEnd方法讀取選中檔案的全部內容
                textBox1.Text = sr.ReadToEnd();
                //關閉當前檔案讀取流
                sr.Close();
            }
        }

 

注意:在表單控制項中添加 openFileDialog1 和 saveFileDialog1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.