ShadyOrb09 ShadyOrb09 - 3 months ago 12
C# Question

How do I replace a part of a line in a text file with user input?

Here's the code.

private void SaveButton_Click(object sender, EventArgs e)
{
string textBoxText = TextBox.Text;

var lines = File.ReadAllLines(@"F:\Bioshock2SP.ini");

foreach(string line in lines)
{
if (line.Contains("VoVolume="))
{
//This is where I get confused.
string settingLine = line;
string replaceline = (line.Replace(line, textBoxText));
File.WriteAllText(@"F:\Bioshock2SP.ini", settingLine);
}
break;
}

MessageBox.Show("Setting saved!");
}


The idea is to replace part of a setting in a Settings.ini file for a game I play, using the user input of a textbox in my form. The user types in a number for example, "1.56" and then hit the Save button to replace the existing line with their input. In this case that setting is the volume.

The application runs completely fine, but after hitting save and going into the settings file my input isn't saved.

Answer

There should be a change in the way you save the file. Save each line of the file as you get it, editing if required.

void SaveButton_Click(object sender, EventArgs e)
{
    var textBoxText = TextBox.Text;

    var lines = File.ReadAllLines(@"F:\Bioshock2SP.ini");

    using (var file = new StreamWriter(@"F:\Bioshock2SP.ini"))
    foreach(string line in lines)
    {
        if (line.Contains("VoVolume="))
            file.WriteLine(line.Substring(0, 9) + textBoxText); // Writes something like 'VoVolume=1.56'
        else file.WriteLine(line); // No editing required
    }

    MessageBox.Show("Setting saved!");
}