【问题标题】:How can write to a text file keys and values and read them back?如何写入文本文件的键和值并将它们读回?
【发布时间】:2015-12-08 02:24:18
【问题描述】:

我做了一个新的形式

private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            label1.Text = "Updating Settings File";
            label1.Visible = true;
            w = new StreamWriter(AuthenticationFileName,true);
            w.WriteLine(cTextBox1.Text);
            w.Close();
            timer1.Start();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            button4.Enabled = false;
            label1.Text = "Updating Settings File";
            label1.Visible = true;
            w = new StreamWriter(AuthenticationFileName,true);
            w.WriteLine(cTextBox2.Text);
            w.Close();
            timer1.Start();
        }

然后在form1中:

string[] lines = File.ReadAllLines(Authentication.AuthenticationFileName);
apiKey = lines[0];
userid = lines[1];
jsonfiledirectory = lines[2];

但问题是在某些情况下 apiKey、userid 和 jsonfiledirectory 的顺序可能不像现在 [0] [1] [2] 因此,只需让 WriteLine 我想为每一行添加一个键和一个值,例如文本文件将如下所示:

apikey = 435345erfsefs54
userid = myttt@walla.com
jsonfiledirectory = c:\

所以当我读回文本文件时,无论行的顺序如何。

【问题讨论】:

  • 帖子缺少对您有什么问题的解释 - 请考虑添加一个(显然它不是写作或阅读,您也不太可能要求字符串拆分或比较)。旁注:发明文件格式是传统程序员过去的时间 - 您尝试创建的文件格式有时称为ini file format(链接也为您提供代码)...
  • ini 作为方法已经很老了,我认为迁移到 JSON 可能会更好,也很容易,如我的回答所示。另一种尝试可能是使用 .config appSettings 来存储这些信息,但我认为 json 更容易
  • Windows 窗体的一个不错的选择是使用设计器创建.settings 文件或创建继承ApplicationSettingsBase 的设置类

标签: c# .net winforms


【解决方案1】:

如何使用 Json.Net (http://www.newtonsoft.com/json),创建一个类来保存您想要序列化/反序列化的属性,然后使用 Json.Net 来处理它们?

很简单,我已经为你做了一个小提琴:https://dotnetfiddle.net/lkkLUv

基本上创建一个类

public class Settings {
    public string ApiKey { get; set;}
    public string UserId { get; set;}
    public string JsonFileDirectory { get; set;}
}

然后读取它(文件当然需要在json中正确格式化)

Settings settings = JsonConvert.DeserializeObject<Settings>(settingsExample);

其中 settingsExample 包含从文件中读取的字符串(如果需要,可以使用 json 直接从文件中读取)

要保存,只需使用 JsonConvert.Serialize(settings) 获取字符串并将其保存到您想要的文件中

【讨论】:

    【解决方案2】:

    有很多解决方案可以保存设置,包括 xml 序列化你的类、使用 ini 文件、使用注册表、使用 json 文件、使用 appsettings,...。

    Windows 窗体应用程序的一个好方法是使用Application Settings

    通过这种方式,您可以使用设计器或代码创建设置类,然后在运行时加载设置、更改值以及保存或重置设置。

    使用设计器创建设置:

    1. 在解决方案资源管理器中,展开项目的“属性”节点并打开 Settings.settings 或根据需要添加新的设置文件。
    2. 在设计器中为您需要的每个设置,您可以设置设置的NameValue 作为默认值,Type 作为设置并选择User 作为范围。这样您就可以在运行时更改设置。

    3. 您可以通过这种方式读取、更改或保存设置:

    //Read and show a value
    MessageBox.Show(Properties.Settings.Default.Key1);
    
    //Changes the value
    Properties.Settings.Default.Key1 = "New Value";
    
    //Save settings (You can do it in a setting form or in close event of your main form)
    Properties.Settings.Default.Save();
    

    以编程方式创建设置:

    1. 在项目中添加一个类并将其命名为MySettings并继承自System.Configuration.ApplicationSettingsBase

    2. 为您需要的每个应用程序设置添加属性。将UserScopedSettingAttribute 添加到该属性。您还可以使用DefaultSettingValue 属性为该属性提供默认值:

    public class MySettings : System.Configuration.ApplicationSettingsBase
    {
        [UserScopedSetting()]
        [DefaultSettingValue("Value1")]
        public string Key1
        {
            get
            {
                return ((string)this["Key1"]);
            }
            set
            {
                this["Key1"] = value;
            }
        }
    }
    

    然后在使用的时候就可以了

    MySettings settnigs;
    
    private void Form1_Load(object sender, EventArgs e)
    {
        settnigs= new MySettings ();
    
        //Read and show a value
        MessageBox.Show(settnigs.Key1);
    
        //Changes the value
        settnigs.Key1 = "New Value";
    }
    
    void Form1_FormClosing(object sender, FormClosingEventArgs 
    {
        settnigs.Save();
    }
    

    要了解有关设置的更多信息:

    【讨论】:

      猜你喜欢
      • 2015-06-26
      • 2021-02-16
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      相关资源
      最近更新 更多