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

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

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

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

试试这个:

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

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

即:

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

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

使用ConfigurationManager获取Configuration -object。 Configuration -object具有字符串属性FilePath 。 请参阅: 配置 – 成员