My Problem:
I am trying to replace a line in a text file with another line based on the condition of the string and a checkbox. For example, there are 2 checkbox, if 1 is checked, it should find string X and replace is with A
If checkbox 2 is checked, it finds string X and replaces it with B
My Research:
I have found that you cannot individually replace a specific line in a text file, but you must rewrite the file and exclude the line. This leaves me with a dilemma since i need that line to be replaced and not just removed. I have made efforts through research
My Efforts:
DialogResult openFile = openFileDialog1.ShowDialog();
if (openFile == DialogResult.OK)
{
string file = openFileDialog1.FileName;
string content = File.ReadAllText(file);
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text File|*.txt";
sfd.FileName = "New Text Doucment";
sfd.Title = "Save As Text File";
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = sfd.FileName;
StreamWriter bw = new StreamWriter(File.Create(path));
bw.WriteLine(content);
bw.Close();
File.WriteAllLines(path, File.ReadAllLines(path).Select(x => string.Format("{0},", x)));
string newContent = File.ReadAllText(path);
newContent = newContent.Remove(newContent.LastIndexOf(","));
File.WriteAllText(path, newContent);
StreamReader reader = new StreamReader(path);
string eachLine = reader.ReadLine();
foreach (char value in newContent)
{
if (eachLine.StartsWith("BRUSH"))
{
if (checkBox1.Checked == true)
{
var oldLines = File.ReadAllLines(path);
var newLines = oldLines.Where(line => !line.Contains("BRUSH"));
File.WriteAllLines(path, newLines);
}
else if (checkBox2.Checked == true)
{
var oldLines = File.ReadAllLines(path);
var newLines = oldLines.Where(line => !line.Contains("BRUSH"));
File.WriteAllLines(path, newLines);
}
}
}
}
}
What i am doing :
Grabbing an existing file,
adding the contents to a new file,
add a comma at the end of each line,
removing the last comma at the end of the file.
And now i need to replace the string in the file
BRUSH
with)),
if checkbox 1 is checked, or replaceBRUSH
withstring.empty
is checkbox 2 is checked