1 回答

TA貢獻1794條經(jīng)驗 獲得超8個贊
我寫了一個小的測試表格,可以做你想做的事。您可以用自己的字符串替換 SNIPPET1 和 SNIPPET2。我的表單上有 2 個復(fù)選框,每個復(fù)選框都會根據(jù)是否選中來添加或刪除片段。您可以修改代碼以滿足您的需要。
請注意,正如上面提到的評論者,您將需要使用 String.Replace() 函數(shù)通過用空白字符串替換它來從文件中刪除文本
public partial class Form1 : Form
{
private const string SNIPPET1 = "Hello world";
private const string SNIPPET2 = "I love Stack";
private const string FILENAME = "output.txt";
private string OutputFile
{
get
{
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FILENAME);
}
}
public Form1()
{
InitializeComponent();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
AddSnippet(SNIPPET1);
}
else
{
RemoveSnippet(SNIPPET1);
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked)
{
AddSnippet(SNIPPET2);
}
else
{
RemoveSnippet(SNIPPET2);
}
}
private void AddSnippet(string snippet)
{
File.AppendAllText(OutputFile, snippet);
}
private void RemoveSnippet(string snippet)
{
// Read in the file
var fileContents = File.ReadAllText(OutputFile);
// Remove the snippet by replacing it with a blank string
fileContents = fileContents.Replace(snippet, String.Empty);
// Write file contents
File.WriteAllText(OutputFile, fileContents);
}
}
- 1 回答
- 0 關(guān)注
- 93 瀏覽
添加回答
舉報