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

时间:2012-01-27 18:15:36

标签: c# winforms configuration settings

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

我理解如何创建路径,这要归功于:Can I control the location of .NET user settings to avoid losing settings on application upgrade?

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

3 个答案:

答案 0 :(得分:20)

试试这个:

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

MessageBox.Show(config.FilePath);

答案 1 :(得分:5)

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

即:

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

请务必在项目的参考资料中使用System.Configuration以便使用它。

答案 2 :(得分:1)

使用ConfigurationManager获取Configuration - 对象。 Configuration - 对象具有字符串属性FilePath。 请参阅:Configuration-Members