简体   繁体   中英

writing/reading strings to/from text file in c#

I am trying to make a simple WindowsForm application that includes about 35 text boxes whos data I want saved at the press of a button into a text file so that I can load the data back into the text boxes when the program starts up. I am having 3 major problems.

  1. figuring out the best way to write the information to a text file
  2. how to specify the path of the text file if it is in the application root directory
  3. how to read from the file at startup (I believe this would happen in Form1_Load )

Here is the code I have been fiddling with that hasn't worked at all. Each textbox should have it's own line in the text file that never changes.

    private void btnSaveCommands_Click(object sender, EventArgs e)
    {
        string path = System.IO.Path.GetDirectoryName("commands");
        var lines = File.ReadAllLines("commands.txt");
        lines[1] = commandTextBox1.Text;
        lines[2] = commandTextBox2.Text;
        lines[3] = commandTextBox3.Text;
        lines[4] = commandTextBox4.Text;
        lines[5] = commandTextBox5.Text;
        etc..... (35 times)
        File.WriteAllLines("commands.txt", lines);
    }

for loading the text I would do something like....

    private void Form1_Load(object sender, EventArgs e)
    {
    string path = System.IO.Path.GetDirectoryName("commands");
    var lines = File.ReadAllLines("commands.txt");
        commandTextBox1.Text = lines[1];
        commandTextBox2.Text = lines[2];
        etc....
    }

I'm not sure if a text file is even the best way to do this kind of thing so if there are any better or easier options please mention them.

I have done some more research and found that a registry might work?

Below is a small example which generates 10 textboxes at run-time, whose content can be saved to a file and reloaded afterwards. The only item that needs to be included inside the form at compile time is a button called saveButton . An important lesson you should learn in comparison to your implementation is to not repeat yourself, à la 35 separate lines to access the textbox. If you can loop it, do it.

    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.IO;
    using System.Text;
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        /// <summary>
        /// The collection of textboxes that need to be added to the form.
        /// </summary>
        private readonly IList<TextBox> inputBoxCollection;

        /// <summary>
        /// The name of the file to save the content to.
        /// </summary>
        private const string Filename = "textbox-text.txt";

        /// <summary>
        /// Initializes a new instance of the <see cref="Form1"/> class.
        /// </summary>
        public Form1()
        {
            this.InitializeComponent();
            this.inputBoxCollection = new List<TextBox>();
            for (var i = 0; i < 10; i++)
            {
                this.inputBoxCollection.Add(new TextBox { Location = new Point(0, i*25) });
            }
        }

        /// <summary>
        /// Handles the Load event of the Form1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void Form1_Load(object sender, EventArgs e)
        {
            var retrievedStrings = File.ReadAllLines(Filename);
            var index = 0;
            foreach (var textBox in this.inputBoxCollection)
            {
                if (index <= retrievedStrings.Length - 1)
                {
                    textBox.Text = retrievedStrings[index++];
                }

                this.Controls.Add(textBox);
            }
        }

        /// <summary>
        /// Handles the Click event of the saveButton control. When pressed, the
        /// content of all the textboxes are stored in a file called textbox-text.txt.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void saveButton_Click(object sender, EventArgs e)
        {
            var builder = new StringBuilder();
            foreach (var textBox in this.inputBoxCollection)
            {
                builder.AppendLine(textBox.Text);
            }

            File.WriteAllText(Filename, builder.ToString());
        }
    }
}

You also asked for better suggestions to saving content to a file. Databases and the registry were banded around, but for this sort of application, a simple text file on disk is ideal. Easily done and easy to maintain.

If your TextBox es have a unique name, then you could do something like this:

public void SaveData(Form form)
{
    var data = form.Controlls
                   .OfType<TextBox>()
                   .ToDictionary(tb => tb.Name, tb => tb.Text);

    SaveToFile(data);
}

public void LoadData(Dictionary<string,string> data, Form form)
{
    var boxes = form.Controlls
                    .OfType<TextBox>()
                    .ToDictionary(tb => tb.Name);

    foreach(var kvp in data)
    {
        boxes[kvp.key].Text = kvp.Value;
    }
}

to do the SaveToFile you could easily use Newtonsoft.Json and to serialize the Dictionary<string, string> like this JsonConvert.SerializeObject(dict) and to get it back: JsonConvert.Deserialize<Dictionary<string,string>>(data) as for the file, you can save anywhere you want as long as you can read it back;

You wrote

I'm not sure if a text file is even the best way to do this kind of thing so if there are any better/easier options plz mention them :)

There's nothing wrong with using the text file. However .Net provides an app.copnfig to store and persist application settings.

Right click on your project and goto the Settings tab. Add an entry for each setting you need. For example

Name             Type               Scope                Value
command1         string             User                 test1
command2         string             User                 test2
additional settings etc

in Form_Load

private void Form1_Load(object sender, EventArgs e)
{
    commandTextBox1.Text = Properties.Settings.Default.command1;
    commandTextBox2.Text = Properties.Settings.Default.command2;
    etc....
}

to Save

private void btnSaveCommands_Click(object sender, EventArgs e)
{
    Properties.Settings.Default.command1 = commandTextBox1.Text;
    Properties.Settings.Default.command2 = commandTextBox2.Text;
    etc..... (35 times)
    Properties.Settings.Default.Save();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM