Codigos Fonte, Artigos e Dicas
Reescrever App.config em tempo de execução!
1º fazer a classe AppConfig.cs
public enum ConfigFileType
{
WebConfig ,
AppConfig
}
<span id="more-17"></span>
public class AppConfig : System.Configuration.AppSettingsReader
{
public string docName = String.Empty;
private XmlNode node=null;
private int _configType;
public int ConfigType
{
get
{
return _configType;
}
set
{
_configType=value;
}
}
public bool SetValue(string key, string value)
{
XmlDocument cfgDoc = new XmlDocument();
loadConfigDoc(cfgDoc);
// retrieve the appSettings node
node = cfgDoc.SelectSingleNode("//connectionStrings");
if( node == null )
{
throw new System.InvalidOperationException("connectionStrings section not found");
}
try
{
// XPath select setting "add" element that contains this key
XmlElement addElem= (XmlElement)node.SelectSingleNode("//add[@name='" +key +"']") ;
if (addElem!=null)
{
addElem.SetAttribute("value",value);
}
// not found, so we need to add the element, key and value
else
{
XmlElement entry = cfgDoc.CreateElement("add");
entry.SetAttribute("name",key);
entry.SetAttribute("connectionString", value);
node.AppendChild(entry);
}
//save it
saveConfigDoc(cfgDoc,docName);
return true;
}
catch
{
return false;
}
}
private void saveConfigDoc(XmlDocument cfgDoc,string cfgDocPath)
{
try
{
XmlTextWriter writer = new XmlTextWriter( cfgDocPath , null );
writer.Formatting = Formatting.Indented;
cfgDoc.WriteTo( writer );
writer.Flush();
writer.Close();
return;
}
catch
{
throw;
}
}
public bool removeElement ( string elementKey)
{
try
{
XmlDocument cfgDoc = new XmlDocument();
loadConfigDoc(cfgDoc);
// retrieve the appSettings node
node = cfgDoc.SelectSingleNode("//connectionStrings");
if( node == null )
{
throw new System.InvalidOperationException("connectionStrings section not found");
}
// XPath select setting "add" element that contains this key to remove
node.RemoveChild( node.SelectSingleNode("//add[@name='" +elementKey +"']") );
saveConfigDoc(cfgDoc,docName);
return true;
}
catch
{
return false;
}
}
private XmlDocument loadConfigDoc( XmlDocument cfgDoc )
{
// load the config file
Console.WriteLine(Convert.ToInt32(ConfigFileType.AppConfig)+"___"+Convert.ToInt32(ConfigType));
if( Convert.ToInt32(ConfigType)==0)
{
docName= ((Assembly.GetEntryAssembly()).GetName()).Name;
docName += ".exe.config";
}
else
{
docName=System.Web.HttpContext.Current.Server.MapPath("web.config");
}
cfgDoc.Load( docName );
return cfgDoc;
}
}
2º Na hora de usar
AppConfig config = new AppConfig();
config.removeElement("localhostcs");
config.SetValue("QUAL KEY QUER MUDAR?", "O QUE QUER ADD?");
ps. o codigo da classe Appconfig.cs esta pronto para mudar a connectio string
portanto prestar atenção na hora de mudar… mude para aquilo que vc quer mudar no seu app.config =D
flw
Posts Relacionados
| Imprimir artigo | Este artigo foi escrito por paulodiogo em 25 25UTC junho 25UTC 2009 às 18:50, e está arquivado em C# Dicas. Siga quaisquer respostas a este artigo através do RSS 2.0. Você pode deixar uma resposta ou fazer um trackback do seu próprio site. |

há 2 anos atrás
Ola estou usando linq to Entities e preciso mudar as conexões dinamicamente mas não estou conseguindo
minha conexão atual é
“);
mas não ta funcionando se vc puder me ajudar?
[Reply]
Paulo Diogo Reply:
agosto 21st, 2009 at 8:45
É esse eu acho q nao se aplicaria… acredito que se você colocar as Connection Strings q vc quer usar no app config da sua aplicação deve funcionar… vou buscar algo pra ser mais exato pra vc =D
[Reply]
jonathas Reply:
agosto 25th, 2009 at 13:32
consigo mudar o app.Config mas as alterações no app.Config só surtem efeito quando recompilo o sistema. VC tem ideia sobre oque posso fazer? para as mudanças em tempo de execução serem reconhecidas pelo linq to Entities
valeu
[Reply]
Paulo Diogo Reply:
agosto 25th, 2009 at 15:07
é meu caro Jonathas, esse era o meu problema na epoca tbm… ja pesquisei um cado e nao consegui encontrar solução para isso =[ eu fiz uma tela a parte, de configuração para mudar o app.config…
Alexandre Santos Reply:
fevereiro 19th, 2010 at 17:49
Me desculpe me entrometer no asssunto de vocês, mas essas mudanças só surtem mesmo quando recompilado o sistema todo? Se abrir e fechar ñ faz diferença?
A solução é falar para o sistema atualizar a sessão na classe ConfigurationManager, exemplo:
ConfigurationManager.RefreshSection(“appSettings”);
Essa linha faz com que na próxima vez que o seu aplicativo for pegar algum falor dessa sessão, ele releia do disco.
No meu caso eu fiz o seguinte:
appSetSec.Settings["hostDB"].Value = txtServer.Text; // Altera o valor da key hostDB
configFile.Save(); // Salva
ConfigurationManager.RefreshSection(“appSettings”); // da um refresh
OBS: quando eu executava o app pelo Visual Studio 2008 e alterava o valor, o valor não era alterado, acho eu que o Visual Studio bloqueava, eu tinha que executar o applicativo (windows form) direto pelo binário.
Abraços….