【问题标题】:How do I get the location of the user.config file in programmatically?如何以编程方式获取 user.config 文件的位置?
【发布时间】:2012-02-20 17:22:45
【问题描述】:

我想在我的 Windows 窗体应用程序中显示 user.config 文件的位置,以便用户可以轻松找到它。

我了解如何创建路径,感谢:Can I control the location of .NET user settings to avoid losing settings on application upgrade?

但是,如果这种情况发生变化,我宁愿不必在我的应用程序中构造路径,尤其是如果有一种简单的方法可以获取 user.config 文件位置。

【问题讨论】:

    标签: c# winforms configuration settings


    【解决方案1】:

    使用ConfigurationManager 获取Configuration 对象。 Configuration-object 有一个字符串属性FilePath。 见:Configuration-Members

    【讨论】:

      【解决方案2】:

      试试这个:

      var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
      
      MessageBox.Show(config.FilePath);
      

      【讨论】:

      • 这正是我所需要的。知道 ConfigurationUserLevel.PerUserRoamingAndLocal 和 ConfigurationUserLevel.PerUserRoaming 之间的真正区别是什么吗? RoamidAndLocal 似乎涵盖了这两种情况???
      • 要获取适用于当前用户的本地配置对象,请将 userLevel 设置为 PerUserRoamingAndLocal。要获取适用于当前用户的漫游配置对象,请将 userLevel 设置为 PerUserRoaming。
      • 如果您发现ConfigurationManager 不存在于您的应用程序中,您可能需要在this stackoverflow answer. 中包含System.Configuration.dll 程序集和using System.Configuration; 的using 语句
      • 投反对票。这个答案缺乏适当的进口。此答案中使用的符号不会显示在 IDE 中。
      • 也许我遗漏了一些东西,但这似乎并不能回答这个问题。我有同样的问题,我想知道,在我的程序中,在运行时,我的程序究竟是从哪个文件中获取其设置的。这给了我三个选项,那是哪个?
      【解决方案3】:

      根据您的应用程序的运行方式,ConfigurationUserLevel.PerUserRoamingAndLocal 可能是您要查找的属性,而不是 ConfigurationUserLevel.PerUserRoaming;

      即:

      var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
      MessageBox.Show(config.FilePath);
      

      确保在项目的引用中包含 System.Configuration 才能使用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-30
        • 1970-01-01
        • 2010-12-04
        • 1970-01-01
        • 2012-01-25
        • 1970-01-01
        相关资源
        最近更新 更多