如何从某些控件构建文本行的内容并将其写入文本文件


private void button1_Click(object sender, EventArgs e)
{
    string accountsSettingsFile = Path.GetDirectoryName(Application.LocalUserAppDataPath)
            + "\accounts" + "\accounts.txt";
    if (!File.Exists(accountsSettingsFile))
        File.Create(accountsSettingsFile);            
    System.IO.File.WriteAllText(accountsSettingsFile,);
}

我想在将内容写入按钮单击事件中的文本文件之前构建一个字符串。也许StringBuilder并格式化它以包含来自某些控件的所有数据。

我有一个textBox1textBox2textBox3 checkBox。我想获取所有这些控件数据并将其行写入文本文件。

例如,如果在textBox1我有"hello",在textBox2 "world"textBox3 "hi"中,checkBoxfalse,那么文本文件内容应该是这样的:

hello
world
hi
false 

我会选择这样的东西,特别是如果你的控件列表以后可能会变长:

    private void button1_Click(object sender, EventArgs e)
    {
      Form1.WriteToFile(textBox1, textBox2, textBox3, checkBox);
    }
    private static void WriteToFile(params Control[] controls)
    {
        string accountsSettingsFile = Path.GetDirectoryName(Application.LocalUserAppDataPath)
        + "\accounts" + "\accounts.txt";
        List<string> lines = new List<string>(controls.Length);
        foreach (var control in controls)
        {
            string value = Form1.GetValueFromControl(control);
            //this will skip null entries, not sure you really
            //want to do that, otherwise when you read this file back in
            //you will have no idea which values represent which fields
            if (value != null)
                lines.Add(value);
        }
        //This will overwrite the file. 
        //If you want to append use File.AppendAllLines
        File.WriteAllLines(accountsSettingsFile, lines);
    }
    private static string GetValueFromControl(Control control)
    {
        if (control is TextBox)
        {
            return ((TextBox)control).Text;
        }
        if (control is CheckBox)
        {
            return ((CheckBox)control).Checked.ToString();
        }
        return null;
    }

但是,由于您将其用于设置,因此将原始值写入文本文件是一种非常脆弱的方法。 我可以建议使用序列化吗?虽然这需要你在项目中引用Newtonsoft.Json(通过nuget):

 private void Button_Write_Click(object sender, EventArgs e)
    {
        AccountSettings settings = new AccountSettings();
        settings.Setting1 = this.textBox1.Text;
        settings.Setting2 = this.textBox2.Text;
        settings.Setting3 = this.textBox3.Text;
        settings.CheckboxValue = this.checkBox.Checked;
        WriteJson(settings, SettingsFile);
    }
    private void Button_Read_Click(object sender, EventArgs e)
    {
        AccountSettings settings = ReadJson<AccountSettings>(SettingsFile);
        this.textBox1.Text = settings.Setting1;
        this.textBox2.Text = settings.Setting2;
        this.textBox3.Text = settings.Setting3;
        this.checkBox.Checked = settings.CheckboxValue;
    }
    private static string SettingsFile
    {
        get
        {
            return Path.GetDirectoryName(Application.LocalUserAppDataPath)
           + "\accounts" + "\accounts.txt";
        }
    }
    private static void WriteJson(Object obj, string path)
    {
        var ser = new JsonSerializer();
        using (var file = File.CreateText(path))
        using (var writer = new JsonTextWriter(file))
        {
            ser.Serialize(writer, obj);
        }
    }
    private static T ReadJson<T>(string path)
        where T: new()
    {
        if (!File.Exists(path))
            return new T();
        var ser = new JsonSerializer();
        using (var file = File.OpenText(path))
        using (var reader = new JsonTextReader(file))
        {
            return ser.Deserialize<T>(reader);
        }
    }
    private class AccountSettings
    {
        public string Setting1 { get; set; }
        public string Setting2 { get; set; }
        public string Setting3 { get; set; }
        public bool CheckboxValue { get; set; }
    }
}

这为您提供了一个强类型的AccountSettings对象,该对象可以以非常具体和可重复的方式编写和读取。

var checked = checkBox.Checked ? "true" : "false";
var textToBeSaved = string.Format("{0}n{1}n{2}n{3}", textBox1.Text, textBox2.Text, textBox3.Text,  checked)
private void button1_Click(object sender, EventArgs e)
{
    string accountsSettingsFile = Path.GetDirectoryName(Application.LocalUserAppDataPath)
            + "\accounts" + "\accounts.txt";
    if (!File.Exists(accountsSettingsFile))
        File.Create(accountsSettingsFile);     
    //New Code
    StringBuilder accountText = new StringBuilder();
    accountText.AppendLine(textbox1.Text);
    accountText.AppendLine(textbox2.Text);       
    accountText.AppendLine(textbox3.Text);
    accountText.AppendLine(checkbox.Checked.ToString().ToLowerInvariant());
    //Above line assumes you want a trailing newline
    System.IO.File.WriteAllText(accountsSettingsFile, accountText.toString());
}

当然,这很无聊,而且不是特别可扩展,如果你想生成一个动态页面,一次输入多个帐户,你可以使用 Page.FindControl 循环浏览文本框并将所有帐户附加到文件中。

最新更新