標籤:
//當點擊開啟的時候 private string files; //建一個成員變數,用來儲存開啟的路徑 private void 開啟OToolStripMenuItem_Click(object sender, EventArgs e) { //openFileDialog1.Filter = "文字檔|*txt|視頻檔案|*avi;*jpg"; //filter建立一個篩選器 //openFileDialog1.ShowDialog(); DialogResult isok = openFileDialog1.ShowDialog(); if (isok == DialogResult.OK) //判斷是否點擊的開啟按鈕 { string filename = openFileDialog1.FileName;//擷取檔案路徑,檔案路徑存在FileName裡 //使用流進行檔案讀取 StreamReader sr = new StreamReader(filename); //構建一個streamreader類的對象sr ,檔案路徑作為參數 textBox1.Text = sr.ReadToEnd(); //readtoend方法,把檔案完全讀出 sr.Close(); //流用完一定關閉 files = filename; }//當點擊另存新檔按鈕的時候 private void 儲存sToolStripMenuItem_Click(object sender, EventArgs e) { saveFileDialog1.Filter = "文字檔|*.txt"; //要儲存的檔案格式。Filter檔案篩選器 DialogResult isok = saveFileDialog1.ShowDialog(); //是否點擊儲存按鈕 if (isok==DialogResult .OK) { string filename = saveFileDialog1.FileName; StreamWriter sw = new StreamWriter(filename); sw.Write(textBox1.Text); sw.Close(); //流用完一定要關閉 } MessageBox.Show(saveFileDialog1 .FileName ); } //當點擊儲存按鈕的時候 private void 另存新檔AToolStripMenuItem_Click(object sender, EventArgs e) { if (files == null) { DialogResult baocun = saveFileDialog1.ShowDialog(); if (baocun == DialogResult.OK) { string filename = saveFileDialog1.FileName; StreamWriter sw = new StreamWriter(filename); sw.Write(textBox1.Text); sw.Close(); } } else { StreamWriter sw = new StreamWriter(files); sw.Write(textBox1.Text); sw.Close(); } } //當點擊顏色的時候 private void 顏色ToolStripMenuItem_Click(object sender, EventArgs e) { //colorDialog1.ShowDialog();//顯示顏色對話方塊,要顯示對話方塊都有showdialog這個共同屬性。。 colorDialog1.ShowDialog()會有一個傳回值,用dialogresult這個枚舉類型來接受 DialogResult dr = colorDialog1.ShowDialog(); if (dr==DialogResult .OK) //判斷是否點擊的確定按鈕 { this.BackColor = colorDialog1.Color; //如果僅僅寫這一句代碼,在選完顏色之後點取消,會預設系統裡的一個黑色 } } //點擊檔案瀏覽器擷取路徑 private void 檔案瀏覽器ToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult dr = folderBrowserDialog1.ShowDialog(); //接受打卡檔案路徑時的傳回值 if (dr==DialogResult .OK) { MessageBox.Show(folderBrowserDialog1.SelectedPath ); //selectedpath擷取路徑的屬性 } } //當點擊建立的時候 private void 建立NToolStripMenuItem_Click(object sender, EventArgs e) { if (textBox1 .Text .Length>0) { saveFileDialog1.ShowDialog(); DialogResult dr = new DialogResult(); if (dr == DialogResult.OK) { string filename = saveFileDialog1.FileName; StreamWriter sw = new StreamWriter(filename); sw.Write(textBox1.Text); sw.Close(); } else { textBox1.Text = ""; } } }
windows form表單應用程式,建一個記事本參考代碼,重點是開啟,儲存,另存新檔