English 中文(简体)
Appsettings 从. config 文件获得值
原标题:AppSettings get value from .config file

我无法访问配置文件中的值 。

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var clientsFilePath = config.AppSettings.Settings["ClientsFilePath"].Value; 
// the second line gets a NullReferenceException

< 加固>. config 文件 :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!-- ... -->
    <add key="ClientsFilePath" value="filepath"/>
    <!-- ... -->
  </appSettings>
</configuration>

你有什么建议吗? 我该怎么做?

最佳回答

这对我管用:

string value = System.Configuration.ConfigurationManager.AppSettings[key];
问题回答

dtsg 给出的作品回答 :

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

但是,您需要添加一个 < 强 > 集合引用 < /强 >

系统. 配置

转到您的 解析探索者 右键点击 引用并选择 Add 引用 。选择 Assembly 标签并搜索 Configation

“https://i.sstatic.net/qHQwS.jpg' alt=“参考管理器”/>

以下是我的 App. config 的例子:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="AdminName" value="My Name"/>
    <add key="AdminEMail" value="MyEMailAddress"/>
  </appSettings>
</configuration>

你可以以下列方式获得:

string adminName = ConfigurationManager.AppSettings["AdminName"];

试一下:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

从配置读取 :

您需要添加引用到配置

  1. Open "Properties" on your project
  2. Go to "Settings" Tab
  3. Add "Name" and "Value"
  4. Get Value with using following code :
string value = Properties.Settings.Default.keyname;

保存到配置 :

Properties.Settings.Default.keyName = value;
Properties.Settings.Default.Save();

我用的是:

    ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
    //configMap.ExeConfigFilename = @"d:	estjustAConfigFile.config.whateverYouLikeExtension";
    configMap.ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + ServiceConstants.FILE_SETTING;
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
    value1 = System.Configuration.ConfigurationManager.AppSettings["NewKey0"];
    value2 = config.AppSettings.Settings["NewKey0"].Value;
    value3 = ConfigurationManager.AppSettings["NewKey0"];

在“强度”值1 =......

然后我决定把内部应用程序配置替换为:

// Note works in service but not in wpf
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"d:	estjustAConfigFile.config.whateverYouLikeExtension");
ConfigurationManager.RefreshSection("appSettings");

string value = ConfigurationManager.AppSettings["NewKey0"];

使用 VS2012.net 4

app/web.config 文件中设置以下配置:

<configuration>
  <appSettings>
    <add key="NameForTheKey" value="ValueForThisKey" />
    ... 
    ...    
  </appSettings>
...
...
</configuration>

然后您可以在代码中输入此行, 从而访问此代码 :

string myVar = System.Configuration.ConfigurationManager.AppSettings["NameForTheKey"];

*Note that this work fine for .net4.5.x and .net4.6.x; but do not work for .net core. Best regards: Rafael

看,我做了我认为是显而易见的事情是:

string filePath = ConfigurationManager.AppSettings.GetValues("ClientsFilePath").ToString();

编译时, 它总是返回无效 。

然而,(以上)这支队伍可以工作:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

很久之后再回到这个...

鉴于配置管理器的消亡, 对于仍在寻找这一尝试答案的任何人来说(例如):

AppSettingsReader appsettingsreader = new AppSettingsReader();
string timeAsString = (string)(new AppSettingsReader().GetValue("Service.Instance.Trigger.Time", typeof(string)));

系统需要,当然要调整

(将代码改写为实际有效且更简单阅读的东西)

有些答案似乎有点离“强”IMO

<add key="ClientsFilePath" value="filepath"/>

确保 System. configifation 被引用。

问题正在询问一个 < 强 > 键 < 强 > / 强 > 的配方 < 强 > 值 < /强 > 。

最肯定的应该是

  string yourKeyValue = ConfigurationManager.AppSettings["ClientsFilePath"]

  //yourKeyValue should hold on the HEAP  "filepath"

这里是一个曲折, 您可以在此将数值组合在一起( 不是为本问题) 。

var emails = ConfigurationManager.AppSettings[ConfigurationManager.AppSettings["Environment"] + "_Emails"];

emails 将是环境密钥+“_Emails”的价值

example :   [email protected];[email protected];

对于网络应用程序, 我通常会写下这个方法, 然后用键调用它。

private String GetConfigValue(String key)
    {
       return System.Web.Configuration.WebConfigurationManager.AppSettings[key].ToString();
    }
  1. Open "Properties" on your project
  2. Go to "Settings" Tab
  3. Add "Name" and "Value"

代码将合并为

    <configuration>
      <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup ..." ... >
          <section name="XX....Properties.Settings" type="System.Configuration.ClientSettingsSection ..." ... />
        </sectionGroup>
      </configSections>
      <applicationSettings>
        <XX....Properties.Settings>
          <setting name="name" serializeAs="String">
            <value>value</value>
          </setting>
          <setting name="name2" serializeAs="String">
            <value>value2</value>
          </setting>
       </XX....Properties.Settings>
      </applicationSettings>
    </configuration>

要获得一个值

属性. settings. Default.Name

属性. settings. default [“名称”]

ConfigurationManager.RefreshSection("appSettings")
string value = System.Configuration.ConfigurationManager.AppSettings[key];

或者您可以同时使用

string value = system.configuration.ConfigurationManager.AppSettings.Get("ClientsFilePath");

//Gets the values associated with the specified key from the System.Collections.Specialized.NameValueCollection

Updated

配置管理器已过时, 您需要使用. NET 环境的 Iconfigation( 由. NET 核心内置自有受扶养人注射提供 ) 。

    private readonly IConfiguration config;

    public MyConstructor(IConfiguration config)
    {
        this.config = config;
    }
    public void DoSomethingFunction()
    {
        string settings1 = config["Setting1"];
    }

您可以简单键入 :

string filePath = Sysem.Configuration.ConfigurationManager.AppSettings[key.ToString()];

因为 keey 是一个对象, 而 appSettings 需要一个字符串

我的简单测试也失败了, 根据这里其他答案的建议- 直到我意识到我添加到桌面应用程序中的配置文件被命名为“ App1. config ” 。 我将它重新命名为“ App. config ”, 并且所有的东西都立即按规定工作。

我不得不在 @System. Configation. Configulation. Configifulation Manager. AppSettings[“钥匙”) 的两侧扔一个在 @System. configation. comfigulation. AppSettings[“钥匙”] 上, 才能把它作为字符串读进我的程序。 我用的是Javascript, 所以这在标签上写着。 注意: ToString () 不为我工作 。

<% 1\\\\\ x\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

string value1 = System.Configuration.ConfigurationManager.AppSettings.Get(0); //for the first key


string value2 = System.Configuration.ConfigurationManager.AppSettings.Get(1); //for the first key




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签