【问题标题】:C# How to set and read controls settings from a text document Win FormsC# 如何从文本文档中设置和读取控件设置 Win Forms
【发布时间】:2016-01-05 21:01:09
【问题描述】:

我需要存储几个热键和一些用户可以在文本文档中选择的设置或其他一些设置,这样当用户重置应用程序时,更改不会重置为默认值。我将需要从几个类访问一些不同的类和控件。我该怎么做?

【问题讨论】:

    标签: c# forms settings controls


    【解决方案1】:

    您可以使用 App.config 文件。

    你的主要代码:

    using System.Configuration;
    
    public class WhateverClassName
    {
         String setting1 = ConfigurationManager.AppSettings["Setting1"];
         // all of your code
    }
    

    然后在 App.config 文件中:

        <?xml version="1.0"?>
        <configuration>
          <appSettings>
            <add key="Setting1" value="whatever the setting value is"/>
          </appSettings>
          <startup>
          <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
          </startup>
        </configuration>
    

    【讨论】:

      【解决方案2】:

      如果您需要保存任何类型的信息或设置,您可以将这些设置保存在一个字符串中,并在每个属性或设置之间使用特定分隔符,然后将该字符串写入.txt 文件,如下所示

      String file = ""; //properties and settings to be saved
      string filePath = "C:\\settings.txt"; //path of the settings.txt file
      FileStream FS = new FileStream(filePath, FileMode.Append);
      StreamWriter SW = new StreamWriter(FS);
      SW.Write(file);
      SW.Close();
      

      [编辑] 当您想读取该文件时(您可以在加载页面时执行此操作),请执行以下操作:

      string file = ""; //string where you'll read from file
      string filePath = "C:\\settings.txt"; //path of the settings.txt file
      FileStream FS = new FileStream(filePath, FileMode.Open);
      StreamReader SR = new StreamReader(FS);
      file = SR.ReadLine;
      SR.Close();
      

      希望这会有所帮助。

      【讨论】:

      • 这看起来像是我的问题的解决方案,但我应该把这个放在什么中只有一个问题?整个班级还是我的主要形式?
      • 老实说,我不确定哪个更好,但如果你把它作为一个函数放在你的代码中,它肯定会同样有效。我希望任何可能知道哪个更正确的人对此提供一些意见,但我确实知道两者肯定会同样有效。并且,检查我刚刚对评论所做的编辑
      【解决方案3】:

      由于C#/.NET 使用 XML,最好使用 .XML 文件来存储您的键值。

      或者,如果您不喜欢 XML 的形式,您可以使用 .ini 文件。

      一个很好的教程如何使用两种方法在这里:http://www.codeproject.com/Articles/5304/Read-Write-XML-files-Config-files-INI-files-or-the

      【讨论】:

        【解决方案4】:

        为什么不使用内置方法来处理设置? https://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-30
          • 1970-01-01
          • 1970-01-01
          • 2013-05-21
          • 1970-01-01
          • 2011-01-14
          • 1970-01-01
          相关资源
          最近更新 更多