在c#中向/从文本文件中写入/读取字符串

时间:2016-06-15 18:26:31

标签: c# text io

我正在尝试创建一个简单的WindowsForm应用程序,其中包含大约35个文本框,其中我想要按下按钮保存的数据到文本文件中,以便我可以在程序启动时将数据加载回文本框。 我有三个主要问题。

  1. 找出将信息写入文本文件的最佳方式
  2. 如果文本文件位于应用程序根目录中,如何指定文本路径
  3. 如何在启动时从文件中读取(我相信这会发生在Form1_Load
  4. 这是我一直在努力的代码,但根本没有用。 每个文本框都应该在文本文件中拥有它永远不会更改的行。

        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);
        }
    

    用于加载文本我会做类似的事情....

        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....
        }
    

    我不确定文本文件是否是执行此类操作的最佳方式,因此如果有更好或更简单的选项,请提及它们。

    我做了一些研究,发现注册表可能有用吗?

3 个答案:

答案 0 :(得分:1)

下面是一个小例子,它在运行时生成10个文本框,其内容可以保存到文件中,然后重新加载。在编译时需要包含在表单内的唯一项是名为saveButton的按钮。与实施相比,您应该学习的一个重要教训是不要重复自己,单独使用35行来访问文本框。如果你可以循环它,那就去做吧。

    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());
        }
    }
}

您还要求提供更好的建议,以便将内容保存到文件中。数据库和注册表被捆绑在一起,但对于这种应用程序,磁盘上的简单文本文件是理想的。易于操作且易于维护。

答案 1 :(得分:0)

如果您的TextBox具有唯一名称,那么您可以执行以下操作:

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;
    }
}

执行SaveToFile您可以轻松使用Newtonsoft.Json并序列化Dictionary<string, string>这样的JsonConvert.SerializeObject(dict)并将其取回:JsonConvert.Deserialize<Dictionary<string,string>>(data)至于{{1}}文件,你可以保存在任何你想要的地方,只要你能读回来;

答案 2 :(得分:0)

你写了

  

我不确定文本文件是否是执行此类操作的最佳方式,因此如果有更好/更简单的选项,请提及它们:)

使用文本文件没有任何问题。但是.Net提供了一个app.copnfig来存储和保存应用程序设置。

右键单击您的项目并转到“设置”选项卡。为您需要的每个设置添加条目。例如

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

在Form_Load

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

保存

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();
}