110,570
社区成员
发帖
与我相关
我的任务
分享
//读取文本
StreamReader sr = new StreamReader(文本文件的路径);
string str = sr.ReadToEnd();
sr.Close();
//替换文本
string [] result = str.Split("\n".ToCharArray());//数组中一个元素代表一行
result[index]="***";//想改哪行自己决定
//更改保存文本
StreamWriter sw = new StreamWriter(文本文件的路径,false);
foreach(string s in result)
sw.WriteLine(s);
sw.Close();
/*当文档状态为新建文档状态时,提示用户输入保存路径.*/
if (saveable == false)
{
string fname;
saveFileDialog1.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.Title = "保存";
saveFileDialog1.InitialDirectory = Application.StartupPath; ;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.ShowDialog();
fname = saveFileDialog1.FileName;
if (fname != "") //文件名不为空时,执行保存;否则放弃操作.
{
richTextBox1.SaveFile(fname, RichTextBoxStreamType.PlainText);
this.Text = this.Text.Substring(1, (this.Text.Length - 1));
/*下面一段代码为:保存文件后打开,下同.*/
richTextBox1.LoadFile(fname, RichTextBoxStreamType.PlainText);
this.Text = fname;
changed=false;
saveable=false;
}
}
/*否则在原文件进行保存*/
else
{
richTextBox1.SaveFile(this.Text.Substring(1, (this.Text.Length - 1)), RichTextBoxStreamType.PlainText);
this.Text = this.Text.Substring(1, (this.Text.Length - 1));
richTextBox1.LoadFile(this.Text, RichTextBoxStreamType.PlainText);
this.Text = this.Text;
changed = false;
}
string fname; //局部变量,保存文件名;下同.
openFileDialog1.FileName = "";
openFileDialog1.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*"; //设定文档过滤器,下同.
openFileDialog1.ShowDialog();
fname = openFileDialog1.FileName;
if (fname != "")
{
richTextBox1.LoadFile(fname, RichTextBoxStreamType.PlainText);
this.Text = fname;
changed = false;
saveable = true;
}