0

I'm trying to write a ip and port to a text file from user input. However the code below only saves part of the created string.

The code I use to write:

private void Edit_Config(string data)
{
    if (File.Exists(file_loc))
    {
        using (StreamWriter edFile = new StreamWriter(file_loc, false))
        {
            edFile.WriteLine(data);
        }
    }
    else
    {
        //File not found, creates new config with new data.
        using (FileStream fs = File.Create(file_loc))
        {
            Byte[] bytes = new UTF8Encoding(true).GetBytes(data);
            fs.Write(bytes, 0, bytes.Length);
        }
    }
}

The code I use to call the command

Edit_Config(txt_serverIP.Text + ":" + txt_port.Text);

What I get in return for example if I put '192.168.2.60:8080' I get '192.168.2.6' saved.

                edFile.Close();

Closing the file fixed the issue.

7
  • Put a Messagebox in the function to display the data string at the start of the routine. The error may be in the calling routine, not here. Commented Jul 26, 2017 at 18:13
  • Message box returns the correct output I should be getting into the file. Commented Jul 26, 2017 at 18:31
  • Does it fail both with a new file and adding to an existing file? Commented Jul 26, 2017 at 18:35
  • The new file also writes in the same fashion of '192.168.2.6', skipping the '0:8080'. Commented Jul 26, 2017 at 18:41
  • I was expecting the new file to be the bit which did it but wondered if it adds it incorrectly to an existing file too. Commented Jul 26, 2017 at 18:44

1 Answer 1

2

As long as your data string is correct, this should handle everything you're doing in that method right now:

private void Edit_Config(string data)
{
    File.AppendAllText(file_loc, data);
}

This should work in embedded framework:

private void Edit_Config(string data)
{
    using (var writer = new StreamWriter(file_loc, true))
    {
       writer.WriteLine(data);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

AppendAllText doesn't work in the embedded framework sadly
Still gives the same result, oddly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.