2012-06-15 1 views
1

Comment lire les chaînes de connexion à partir du fichier de configuration personnalisé (disons abc.config) en utilisant WebConfigurationManager du code C# d'asp.net?lire le fichier de configuration personnalisé dans asp.net

Configuration conf = WebConfigurationManager.OpenWebConfiguration("~/abc.config"); 

Cela ne semble pas fonctionner.

+0

Que voulez-vous dire ne semble pas fonctionner? Avez-vous une exception? Est-ce que ce n'est pas chargé? Quel est le bahvior? –

+0

Vérifiez votre «chemin de configuration» correctement. Cela devrait être simple. L'objet 'conf' est-il nul? –

+0

Il lit un SQLEXPRESS comme source de données (une chaîne de connexion différente) pas de abc.config – Sam

Répondre

1

Je ne pense pas que vous pouvez le lire avec webconfigurationmanager. vous aurez lu comme un fichier xml comme il est un fichier xml

public static string GetSingleValue(string strXPathExpression, string strAttributeName) 
     { 
      XmlNode node = GetNode(strXPathExpression); 
      if (node != null) 
      { 
       XmlAttribute attribute = node.Attributes[strAttributeName]; 
       if (attribute != null) 
        return attribute.Value; 
      } 

      return string.Empty; 


     } 
+0

Est-ce exact? – Sam

+0

OUI, Selon mes connaissances – Rab

3

vous pouvez utiliser cette astuce: est mon méthodolo- personnalisé à l'aide webapp.config de la racine web. readl tous les paramètres de l'application et le retour;

//Read WebAppConfiguration 
public static AppSettingsSection ReadAllWebappConfig() 
{ 
    string physicalWebAppPath = ""; 
    AppSettingsSection appSettings; 

    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); 
    physicalWebAppPath = System.Web.Hosting.HostingEnvironment.MapPath("~/webapp.config"); 

    if (System.IO.File.Exists(physicalWebAppPath)) 
    { 
     fileMap.ExeConfigFilename = physicalWebAppPath; 
     Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); 
     appSettings = (AppSettingsSection)config.GetSection("appSettings"); 
    } 
    else 
     appSettings = null; 

    return appSettings; 
} 

échantillon webapp.config:

<configuration> 
    <appSettings> 
    <add key="WebApp-FixedTopMenu" value="true"/> 
    <add key="WebApp-FixedTopMenuThickness" value="true"/> 
    </appSettings> 
</configuration> 
+0

Que faire si je n'ai pas de nœud appSettings? – Shesha

+0

Tous les fichiers XML ont besoin d'un élément racine et d'un élément, c'est un XML standard. Vous avez besoin de l'élément racine (configuration) et de l'élément Item (appSettings) et de vos propriétés désirées (par exemple WebApp-FixedTopMenu). – mRizvandi

Questions connexes