对于我来说,有一个更好的方法来进行streamWrite而不需要为我按下的每个按钮重复代码吗?下面是我正在处理的示例,其中一个按钮执行它自己的事情并相应地写入元音,另一个执行相同的操作,除非它相应地写入没有字母字符:
private void btnVowels_Click(object sender, EventArgs e)
{
string wholeText = "";
string copyText = richTextBox1.Text;
if (System.IO.File.Exists(Second_File) == true)
{
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(Second_File);
string vowels = "AaEeIiOoUu";
copyText = new string(copyText.Where(c => !vowels.Contains(c)).ToArray());
wholeText = richTextBox1.Text + copyText;
objWriter.Write(wholeText);
richTextBox2.Text = wholeText;
objWriter.Close();
}
else
{
MessageBox.Show("No file named " + Second_File);
}
}
private void btnAlpha_Click(object sender, EventArgs e)
{
string wholeText = "";
string copyText = richTextBox1.Text;
if (System.IO.File.Exists(Second_File) == true)
{
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(Second_File);
string nonAlpha = @"[^A-Za-z ]+";
string addSpace = "";
copyText = Regex.Replace(copyText, nonAlpha, addSpace);
objWriter.Write(wholeText);
richTextBox2.Text = wholeText;
objWriter.Close();
}
else
{
MessageBox.Show("No file named " + Second_File);
}
}
答案 0 :(得分:2)
您可以使用一个常用功能来处理将内容写入文件并更新第二个文本框:
private void btnAlpha_Click(object sender, EventArgs e)
{
string nonAlpha = @"[^A-Za-z ]+";
string addSpace = "";
string copyText = richTextBox1.Text;
copyText = Regex.Replace(copyText, nonAlpha, addSpace);
WriteToFile(Second_File, wholeText);
}
private void btnVowels_Click(object sender, EventArgs e)
{
string vowels = "AaEeIiOoUu";
string copyText = richTextBox1.Text;
copyText = new string(copyText.Where(c => !vowels.Contains(c)).ToArray());
string wholeText = richTextBox1.Text + copyText;
WriteToFile(Second_File, wholeText);
}
private void WriteToFile(string filename, string contents)
{
if (File.Exists(filename))
{
File.WriteAllText(filename, contents);
richTextBox2.Text = wholeText;
}
else
{
MessageBox.Show("No file named " + filename);
}
}
答案 1 :(得分:1)
为什么不这样做?
private void Write(string file, string text)
{
if (File.Exists(file))
{
using (StreamWriter objWriter = new StreamWriter(file))
{
objWriter.Write(text);
}
}
else
{
MessageBox.Show("No file named " + file);
}
}
private void btnAlpha_Click(object sender, EventArgs e)
{
string wholeText = "";
string copyText = richTextBox1.Text;
string nonAlpha = @"[^A-Za-z ]+";
string addSpace = "";
copyText = Regex.Replace(copyText, nonAlpha, addSpace);
wholeText = richTextBox1.Text + copyText;
Write(Second_File, wholeText); // same for the second button
richTextBox2.Text = wholeText;
}