1.读取文件:
OpenFileDialog dialog=new OpenFileDialog(); dialog.InitialDirectory = Application.StartupPath; dialog.Filter = "All Files|*.*|text file(*.txt)|*.txt"; dialog.RestoreDirectory = true; if (dialog.ShowDialog() == DialogResult.OK) { string filepath = dialog.FileName.ToString(); string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); textBox1.Text = filepath; using (StreamReader sr = new StreamReader(filepath, Encoding.Default))//如果乱码,可改为System.Text.Encoding.UTF-8;或者System.Text.Encoding.GBK { string str; string line=""; while ((str = sr.ReadLine()) != null) { line+=str+"\n"; } richTextBox1.Text = line; } }
注:通过拖拽文件打开文件:
private void Form1_DragEnter(object sender, DragEventArgs e) { string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString(); textBox1.Text = path; //将获取到的完整路径赋值到textBox1 using (StreamReader sr = new StreamReader(path, Encoding.Default))//如果乱码,可改为System.Text.Encoding.UTF-8;或者System.Text.Encoding.GBK { string str; string line = ""; while ((str = sr.ReadLine()) != null) { line += str + "\n"; } richTextBox1.Text = line; } }
2.去除空行:
richTextBox1.Clear(); string[] xynet = File.ReadAllLines(textBox1.Text, Encoding.Default); for (int i = 0; i < xynet.Length; i++) { if (xynet[i].Trim() == "") { } else { richTextBox1.Text+= xynet[i]+"\n"; } }
3.保存:
if (this.richTextBox1.Text == "") return; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.DefaultExt = "txt"; saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; if (saveFileDialog1.ShowDialog() == DialogResult.Cancel) return; string FileName = saveFileDialog1.FileName; richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
4.清空:
textBox1.Text = string.Empty; richTextBox1.Text = string.Empty;