Reputation: 137
In my C# script, there are a list of check-boxes that, when ticked, adds a line of text to a text file. And when unticked, remove that piece of text from the file. My problem is, I don't know how the code will recognise the line to remove as they can be in any order.
Upvotes: 0
Views: 62
Reputation: 3255
I've written a small test form that will do what you want. You can replace SNIPPET1 and SNIPPET2 with your own strings. I have 2 checkboxes on my form, each one will add or remove the snippet based on whether it's checked on or off. You can modify the code to suit what you need.
Please note, as the commenter above mentioned, you will need to use the String.Replace() function to remove the text from the file by replacing it with a blank string
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);
}
}
Upvotes: 1