复选框删除并在列表中创建一段文本

在我的 C# 脚本中,有一个复选框列表,勾选后会向文本文件添加一行文本。取消选中时,从文件中删除该段文本。我的问题是,我不知道代码将如何识别要删除的行,因为它们可以按任何顺序排列。



慕森王
浏览 63回答 1
1回答

幕布斯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);        }    }
打开App,查看更多内容
随时随地看视频慕课网APP