【问题标题】:Ensuring that App.config Exists Before Using It [duplicate]在使用之前确保 App.config 存在 [重复]
【发布时间】:2012-06-21 02:00:58
【问题描述】:

可能重复:
how to determine whether app.config file exists

有没有办法在尝试访问值之前确保 App.config 存在?我不想在执行此操作时遇到“对象引用未设置为对象错误的实例”的情况:

machineName = appConfig.AppSettings.Settings["MachineName"].Value;

如果找不到我的 App.config,我不确定如何知道它是否存在或 appConfig 对象是否已正确填充。我试过了

if (appConfig.AppSettings.Settings.Count == 0) { // do something }

但我不确定这是否是最好的方法。

【问题讨论】:

标签: c# .net


【解决方案1】:

与其检查 App.config 是否存在,为什么不对值进行空检查?当您在空值上调用该方法时会发生错误。

if (appConfig.AppSettings.Settings["MachineName"] != null)
{
    machineName = appConfig.AppSettings.Settings["MachineName"].Value;
}

【讨论】:

    猜你喜欢
    • 2016-07-21
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2018-10-21
    • 2015-04-20
    • 2020-06-16
    相关资源
    最近更新 更多