2010-07-29 4 views
4

J'ai pris le code de cet exemple.System.Configuration avec le fichier .config séparé

http://msdn.microsoft.com/en-us/library/2tw134k3.aspx

Ce que je me demande (et je suis allé partout dans la recherche Internet aujourd'hui) ... Comment obtenez-vous que pour être dans un fichier externe (séparé).

L'idée que je vais faire est:

<configuration> 
    <configSections> 
    <sectionGroup name="pageAppearanceGroup"> 
     <section 
     name="pageAppearance" 
     type="HelperAssembly.Configuration.PageAppearanceSection,HelperAssembly" 
     allowLocation="true" 
     allowDefinition="Everywhere" 
     /> 
    </sectionGroup> 
    </configSections> 


    <pageAppearanceGroup fileName="SomeSeparateFile.config"/> 

</configuration> 

..................

qui précède ne fonctionne pas (bien sûr).

Ci-dessous est mon copiage/collage de l'article ms mentionné ci-dessus. Et ça fonctionnait complètement quand je l'ai collé ici.

//START HelperAssembly.csproj 

namespace HelperAssembly.Configuration 
{ 
    using System; 
    using System.Collections; 
    using System.Text; 
    using System.Configuration; 
    using System.Xml; 

    public class PageAppearanceSection : ConfigurationSection 
    { 
     // Create a "remoteOnly" attribute. 
     [ConfigurationProperty("remoteOnly", DefaultValue = "false", IsRequired = false)] 
     public Boolean RemoteOnly 
     { 
      get 
      { 
       return (Boolean)this["remoteOnly"]; 
      } 
      set 
      { 
       this["remoteOnly"] = value; 
      } 
     } 

     // Create a "font" element. 
     [ConfigurationProperty("font")] 
     public FontElement Font 
     { 
      get 
      { 
       return (FontElement)this["font"]; 
      } 
      set 
      { this["font"] = value; } 
     } 

     // Create a "color element." 
     [ConfigurationProperty("color")] 
     public ColorElement Color 
     { 
      get 
      { 
       return (ColorElement)this["color"]; 
      } 
      set 
      { this["color"] = value; } 
     } 
    } 

    // Define the "font" element 
    // with "name" and "size" attributes. 
    public class FontElement : ConfigurationElement 
    { 
     [ConfigurationProperty("name", DefaultValue = "Arial", IsRequired = true)] 
     [StringValidator(InvalidCharacters = "[email protected]#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)] 
     public String Name 
     { 
      get 
      { 
       return (String)this["name"]; 
      } 
      set 
      { 
       this["name"] = value; 
      } 
     } 

     [ConfigurationProperty("size", DefaultValue = "12", IsRequired = false)] 
     [IntegerValidator(ExcludeRange = false, MaxValue = 24, MinValue = 6)] 
     public int Size 
     { 
      get 
      { return (int)this["size"]; } 
      set 
      { this["size"] = value; } 
     } 
    } 

    // Define the "color" element 
    // with "background" and "foreground" attributes. 
    public class ColorElement : ConfigurationElement 
    { 
     [ConfigurationProperty("background", DefaultValue = "FFFFFF", IsRequired = true)] 
     [StringValidator(InvalidCharacters = "[email protected]#$%^&*()[]{}/;'\"|\\GHIJKLMNOPQRSTUVWXYZ", MinLength = 6, MaxLength = 6)] 
     public String Background 
     { 
      get 
      { 
       return (String)this["background"]; 
      } 
      set 
      { 
       this["background"] = value; 
      } 
     } 

     [ConfigurationProperty("foreground", DefaultValue = "000000", IsRequired = true)] 
     [StringValidator(InvalidCharacters = "[email protected]#$%^&*()[]{}/;'\"|\\GHIJKLMNOPQRSTUVWXYZ", MinLength = 6, MaxLength = 6)] 
     public String Foreground 
     { 
      get 
      { 
       return (String)this["foreground"]; 
      } 
      set 
      { 
       this["foreground"] = value; 
      } 
     } 

    } 

} 



    namespace HelperAssembly.Configuration 
{ 
    using System; 
    using System.Configuration; 

    public static class ConfigurationRetriever 
    { 
     public static PageAppearanceSection RetrievePageAppearanceSection1() 
     { 
      PageAppearanceSection config = (PageAppearanceSection)System.Configuration.ConfigurationManager.GetSection("pageAppearanceGroup/pageAppearance"); 
      return config; 
     } 
} 
} 



//START ConsoleApplication1.csproj 

    using System; 

    using HelperAssembly.Configuration; 

    namespace ConsoleApplication1 
    { 
     class Program 
     { 
     static void Main(string[] args) 
     { 

      try 
      { 
       PageAppearanceSection pas = ConfigurationRetriever.RetrievePageAppearanceSection1(); 
       if (null != pas) 
       { 
        Console.WriteLine(pas.Color.Foreground); 
        Console.WriteLine(pas.Color.Background); 
       } 
      } 

      catch (Exception ex) 
      { 
       Exception innerException = ex; 
       while (null != innerException) 
       { 
        Console.WriteLine(innerException.Message); 
        Console.WriteLine("\n\r"); 

        Console.WriteLine(innerException.StackTrace); 
        Console.WriteLine("\n\r"); 

        innerException = innerException.InnerException; 
       } 
      } 

      Console.WriteLine("Press Enter"); 
      Console.ReadLine(); 

     } 
    } 
    } 



//XML for config file that works with the above code 


    <?xml version="1.0" encoding="utf-8" ?> 
    <configuration> 
     <configSections> 
     <sectionGroup name="pageAppearanceGroup"> 
      <section 
     name="pageAppearance" 
     type="HelperAssembly.Configuration.PageAppearanceSection,HelperAssembly" 
     allowLocation="true" 
     allowDefinition="Everywhere" 
     /> 
    </sectionGroup> 
    </configSections> 

    <pageAppearanceGroup> 
    <pageAppearance remoteOnly="true"> 
     <font name="TimesNewRoman" size="18"/> 
     <color background="DEFDEF" foreground="ABCABC"/> 
     </pageAppearance> 
    </pageAppearanceGroup> 

    </configuration> 
+0

Pour inclure du code et/ou XML sur ce site, sélectionnez-le dans l'éditeur et appuyez sur Ctrl-K. –

+0

BTW, avez-vous apporté des modifications au code que vous avez collé? –

+0

Aucun changement. La seule chose que j'ai faite a été de mettre un espace après le dans le xml. Mais le code C# en tant que copier et coller, et j'ai utilisé le tagger "code" dans le contrôle du bloc de texte. – granadaCoder

Répondre

5
+0

Il y a un attribut peu connu qui a été introduit dans le .Net framework 2.0 appelé configSource, qui vous permet d'externaliser des sections du fichier de configuration. mais peut être ajouté à une section de configuration pour spécifier un fichier externe pour cette section: Le ci-dessus est une citation de la première URL. (Dans le cas où il cesse d'exister dans le futur). // attribut inconnu // Fin de citation Maintenant, je ne me sens pas si mal. MERCI! – granadaCoder

9

Cela fonctionnera si vous changez votre app.config utiliser ceci:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <configSections> 
    <sectionGroup name="pageAppearanceGroup"> 
     <section 
     name="pageAppearance" 
     type="HelperAssembly.Configuration.PageAppearanceSection,HelperAssembly" 
     allowLocation="true" 
     allowDefinition="Everywhere" 
     /> 
    </sectionGroup> 
    </configSections> 

    <pageAppearanceGroup> 
    <pageAppearance configSource="SomeSeparateFile.config"/> 
    </pageAppearanceGroup> 

</configuration> 

Et votre someSeparateFile. config pour ressembler à ceci:

<pageAppearance remoteOnly="true"> 
    <font name="TimesNewRoman" size="18"/> 
    <color background="123456" foreground="ABCDEF"/> 
</pageAppearance> 

(aucun élément configuration dans ce fichier!)

J'ai été en mesure de se déplacer configSections dans des fichiers séparés. Vous n'êtes pas sûr de pouvoir le faire avec configGroups à moins de faire beaucoup plus de programmation. Le modèle de cadre de configuration vous permet de déplacer configSections assez facilement.

Espérons que cela aide !!

+0

// Citation // Je ne suis pas sûr que vous puissiez le faire avec configGroups, sauf si vous faites beaucoup plus de programmation.// Citation Je restais simplement "vrai" à l'exemple msdn d'origine sur celui-là. (je pense) la chose supplémentaire configGroups est plus de problèmes que cela en vaut la peine. Merci. ... – granadaCoder

+0

Merci l'homme, c'était utile. – Anvar

+0

@Anvar - pas de problème ... content que je puisse être utile! –

Questions connexes