Search code examples
c#winformsstreamreaderopenfiledialog

Open/save multiple textbox values c# windows forms


I created simple example and I can't find solution anywhere. I want to save UI textbox data, and open it in another(same) windows form file. Here is code example:

private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                StreamWriter write = new StreamWriter(File.Create(sfd.FileName));
                write.Write(txtFirstInput.Text);
                write.Write(txtSecondInput.Text);
                write.Close();
                write.Dispose();
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if(ofd.ShowDialog() == DialogResult.OK)
            {
                StreamReader read = new StreamReader(File.OpenRead(ofd.FileName));
                txtFirstInput.Text = read.ReadLine();
                txtSecondInput.Text = read.ReadLine();
                read.Close();
                read.Dispose();
            }
        }

The problem I get here is that all inputed data get in first textbox. How to separate it? What is the easiest and most efficient way? Should I create and use byte buffer (and HxD) for streaming through user input?

Can someone please give me some directions or examples.

Thank you for your time


Solution

  • You use ReadLine to read data back, so you need to use WriteLine when writing data to disk

    private void btnSave_Click(object sender, EventArgs e)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            using(StreamWriter write = new StreamWriter(File.Create(sfd.FileName)))
            {
                write.WriteLine(txtFirstInput.Text);
                write.WriteLine(txtSecondInput.Text);
            }
        }
    }
    

    Using Write, the data is written to disk without a line carriage return and so it is just on one single line. When you call ReadLine all the data is read and put on the first textbox.

    Also notice that it is always recommended to enclose a IDisposable object like the StreamWriter inside a using statement. This approach will ensure that your Stream is correctly closed and disposed also in case of exceptions. (The same should be applied to the StreamReader below)