在打開UAC的情況下,窗體應用程序默認配置信息的讀取與寫入,在 Program Files 文件夾下將會引發一些錯誤。
研究了很多朋友,多是通過提升應用程序權限,要求用戶以管理員身份使用軟件的方式,來解決這個問題。
提升權限來回避UAC的控制,這種解決方式,并不妥當。
研究了幾天,轉了好大一圈,終于初步解決了這個問題,半夜三更,擔心解決的徹底,在此拋磚引玉,希望完美解決問題。
-----------------------------------------------------------------------------------------
代碼
public 構造函數()
{
ExeConfigurationFileMap tmp = new ExeConfigurationFileMap();
tmp.ExeConfigFilename = ConfigerFile();
ShiQiangConfiger = ConfigurationManager.OpenMappedExeConfiguration(tmp, ConfigurationUserLevel.None);
}
//-------------------------------------------------------------------//
private string ConfigerFile()
{
string rtnValue = string.Empty;
int targetIndex = Application.ExecutablePath.LastIndexOf(@"");
if (targetIndex >= 0)
{
if (!System.IO.Directory.Exists(Application.CommonAppDataPath))
{
System.IO.Directory.CreateDirectory(Application.CommonAppDataPath);
}
rtnValue = System.IO.Path.Combine(Application.CommonAppDataPath, Application.ExecutablePath.Substring(targetIndex + 1) + ".Config");
if (!System.IO.File.Exists(rtnValue))
{
//如果沒文件的話,復制app.config,在CommonAppDataPath處創建個新的。
System.Configuration.Configuration tmp = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
tmp.SaveAs(rtnValue);
}
}
return rtnValue;
}
private System.Configuration.Configuration myConfiguration;
下面用 myConfiguration 就可以進行通常的配置文件操作了。
原文:http://www.cnblogs.com/sasbya/archive/2010/05/05/1727632.html