Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从一些控件构建文本行内容并将其写入文本文件?_C#_.net_Winforms - Fatal编程技术网

C# 如何从一些控件构建文本行内容并将其写入文本文件?

C# 如何从一些控件构建文本行内容并将其写入文本文件?,c#,.net,winforms,C#,.net,Winforms,我想在button click事件中将内容写入文本文件之前构建一个字符串。可能是StringBuilder,并对其进行格式化以包含来自某些控件的所有数据 我有一个textBox1,textBox2,textBox3a复选框。 我想获取所有这些控件数据,并将其以行形式写入文本文件 例如,如果在textBox1中我有“hello”,在textBox2“world”和textBox3“hi”中,并且复选框为false,则文本文件内容应类似于: private void button1_Click(ob

我想在button click事件中将内容写入文本文件之前构建一个字符串。可能是
StringBuilder
,并对其进行格式化以包含来自某些控件的所有数据

我有一个
textBox1
textBox2
textBox3
a
复选框
。 我想获取所有这些控件数据,并将其以行形式写入文本文件

例如,如果在
textBox1
中我有
“hello”
,在
textBox2
“world”和
textBox3
“hi”中,并且
复选框
false
,则文本文件内容应类似于:

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

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

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按钮1\u单击(对象发送者,事件参数e)
{
Form1.WriteToFile(textBox1、textBox2、textBox3、复选框);
}
私有静态void WriteToFile(参数控件[]控件)
{
string accountsSettingsFile=Path.GetDirectoryName(Application.LocalUserAppDataPath)
+“\\accounts”+“\\accounts.txt”;
列表行=新列表(controls.Length);
foreach(控件中的var控件)
{
字符串值=Form1.GetValueFromControl(控件);
//这将跳过空条目,不确定您是否真的
//要这样做,否则当您读回此文件时
//您将不知道哪些值表示哪些字段
if(值!=null)
行。添加(值);
}
//这将覆盖该文件。
//如果要追加,请使用File.AppendAllLines
File.writeAllines(accountsSettingsFile,行);
}
私有静态字符串GetValueFromControl(控件控件)
{
如果(控件为文本框)
{
返回((文本框)控件).Text;
}
如果(控件为复选框)
{
返回((复选框)控件).Checked.ToString();
}
返回null;
}
不过,由于您将此用于设置,因此将原始值写入文本文件是一种非常脆弱的方法。我可以推荐使用序列化吗?尽管这要求您在项目中引用Newtonsoft.Json(通过nuget):

    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;
    }
private void按钮\写入\单击(对象发送者,事件参数e)
{
AccountSettings=新的AccountSettings();
settings.Setting1=this.textBox1.Text;
settings.Setting2=this.textBox2.Text;
settings.Setting3=this.textBox3.Text;
settings.CheckboxValue=this.checkBox.Checked;
WriteJson(设置、设置文件);
}
私有无效按钮\u读取\u单击(对象发送者,事件参数e)
{
AccountSettings=ReadJson(设置文件);
this.textBox1.Text=settings.Setting1;
this.textBox2.Text=settings.Setting2;
this.textBox3.Text=settings.Setting3;
this.checkBox.Checked=settings.CheckboxValue;
}
私有静态字符串设置文件
{
得到
{
返回Path.GetDirectoryName(Application.LocalUserAppDataPath)
+“\\accounts”+“\\accounts.txt”;
}
}
私有静态void WriteJson(对象对象对象,字符串路径)
{
var ser=新的JsonSerializer();
使用(var file=file.CreateText(路径))
使用(var writer=newjsontextwriter(文件))
{
序列序列化(编写器,对象);
}
}
私有静态T ReadJson(字符串路径)
其中T:new()
{
如果(!File.Exists(path))
返回新的T();
var ser=新的JsonSerializer();
使用(var file=file.OpenText(路径))
使用(var reader=newjsontextreader(文件))
{
返回序列反序列化(读取器);
}
}
私有类帐户设置
{
公共字符串设置1{get;set;}
公共字符串设置2{get;set;}
公共字符串设置3{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 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; }
    }

}
private void按钮1\u单击(对象发送者,事件参数e)
{
Form1.WriteToFile(textBox1、textBox2、textBox3、复选框);
}
私有静态void WriteToFile(参数控件[]控件)
{
string accountsSettingsFile=Path.GetDirectoryName(Application.LocalUserAppDataPath)
+“\\accounts”+“\\accounts.txt”;
列表行=新列表(controls.Length);
foreach(控件中的var控件)
{
字符串值=Form1.GetValueFromControl(控件);
//这将跳过空条目,不确定您是否真的
//要这样做,否则当您读回此文件时
//您将不知道哪些值表示哪些字段
if(值!=null)
行。添加(值);
}
//这将覆盖该文件。
//如果要追加,请使用File.AppendAllLines
File.writeAllines(accountsSettingsFile,行);
}
私有静态字符串GetValueFromControl(控件控件)
{
如果(控件为文本框)
{
返回((文本框)控件).Text;
}
如果(控件为复选框)
{
返回((复选框)控件).Checked.ToString();
}
返回null;
}
不过,由于您将此用于设置,因此将原始值写入文本文件是一种非常脆弱的方法。我可以推荐使用序列化吗?尽管这要求您在项目中引用Newtonsoft.Json(通过nuget):

    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;
    }
private void按钮\写入\单击(对象发送者,事件参数e)
{
帐户设置