如何以编程方式获取user.config文件的位置?

Chr*_*ber 12 c# settings configuration winforms

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

我理解如何创建路径,这要归功于:我可以控制.NET用户设置的位置以避免丢失应用程序升级的设置吗?.

但是,如果这种情况发生变化,我宁愿不必在我的应用程序中构建路径,特别是如果有一个简单的方法来获取user.config文件位置.

Fra*_*cis 20

试试这个:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);

MessageBox.Show(config.FilePath);
Run Code Online (Sandbox Code Playgroud)

  • 这正是我所需要的.知道ConfigurationUserLevel.PerUserRoamingAndLocal和ConfigurationUserLevel.PerUserRoaming之间的真正区别是什么?RoamindAndLocal似乎涵盖了两种情况??? (2认同)
  • 要获取适用于当前用户的本地配置对象,请将 userLevel 设置为 PerUserRoamingAndLocal。要获取适用于当前用户的漫游配置对象,请将 userLevel 设置为 PerUserRoaming。 (2认同)
  • 如果您发现应用程序中不存在 `ConfigurationManager`,则可能需要包含 System.Configuration.dll 程序集和 `using System.Configuration;` 的 using 语句 [this stackoverflow answer.](https:// stackoverflow.com/questions/1796851/unable-to-access-configurationmanager-appsettings-in-a-windows-forms-application) (2认同)

c0g*_*c0g 5

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

即:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
MessageBox.Show(config.FilePath);
Run Code Online (Sandbox Code Playgroud)

确保在项目的引用中有System.Configuration以便使用它.