幕布斯7119047
我写了一个小的测试表格,可以做你想做的事。您可以用自己的字符串替换 SNIPPET1 和 SNIPPET2。我的表单上有 2 个复选框,每个复选框都会根据是否选中来添加或删除片段。您可以修改代码以满足您的需要。请注意,正如上面提到的评论者,您将需要使用 String.Replace() 函数通过用空白字符串替换它来从文件中删除文本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); } }