2009-06-26 21 views
17

Supongamos que tengo un archivo de configuración personalizado que corresponde a una ConfigurationSection personalizados definidos y los elementos de configuración. Estas clases de configuración se almacenan en una biblioteca.Cómo cargar archivo de configuración mediante programación

archivo de configuración se parece a esto

<?xml version="1.0" encoding="utf-8" ?> 
<Schoool Name="RT"> 
    <Student></Student> 
</Schoool> 

¿Cómo puedo cargar mediante programación y utilizar este archivo de configuración del Código?

no quiero utilizar el control XML sin procesar, pero aprovechar las clases de configuración ya definidos.

+2

¿por qué no elige la respuesta seleccionada? –

Respuesta

7

Salida serie de tres partes de Jon Rista en .NET 2.0 configuración arriba en CodeProject.

Muy recomendable, bien escrito y muy útil!

Realmente no se puede cargar cualquier fragmento XML - lo que puede carga es un archivo de configuración completa, aparte que se ve y se siente como app.config.

Si desea crear y diseñar sus propias secciones de configuración personalizadas, también debería verificar el Configuration Section Designer en CodePlex, un complemento de Visual Studio que le permite diseñar visualmente las secciones de configuración y tener todo el código de plomería necesario generado tú.

+6

Esto es útil, pero no una respuesta a la pregunta. Leo los tres artículos y todavía no soy tan inteligente. –

+1

@Andrew Myhre: Estaba tratando de decir: en lugar de enrollar el tuyo y reinventar la rueda, usa lo que ya está disponible en .NET Framework. ¡Deja de reinventar la rueda! Ya hay suficientes ruedas: ¡úsalos! –

2

El atributo configSource le permite mover cualquier elemento de configuración en un archivo separado. En su app.config principal que haría algo como esto:

<configuration> 
    <configSections> 
    <add name="schools" type="..." /> 
    </configSections> 

    <schools configSource="schools.config /> 
</configuration> 
+0

Verdadero, pero incluso en este caso, debe crear su propio elemento de configuración personalizado para la parte de definición . –

+0

@marc_s: mientras leo el OP, el autor ya tiene una "sección de configuración personalizada", pero no está seguro de cómo utilizar esto como un "archivo de configuración personalizada". Sin embargo, podría estar equivocado. –

+0

Podrías tener razón :-) Supongo que no leí la pregunta con cuidado - mea culpa. –

15

Vas a tener que adaptarlo a sus necesidades, pero aquí está el código que utilizo en uno de mis proyectos para hacer precisamente eso:

var fileMap = new ConfigurationFileMap("pathtoconfigfile"); 
var configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap); 
var sectionGroup = configuration.GetSectionGroup("applicationSettings"); // This is the section group name, change to your needs 
var section = (ClientSettingsSection)sectionGroup.Sections.Get("MyTarget.Namespace.Properties.Settings"); // This is the section name, change to your needs 
var setting = section.Settings.Get("SettingName"); // This is the setting name, change to your needs 
return setting.Value.ValueXml.InnerText; 

Tenga en cuenta que estoy leyendo un archivo de configuración .net válida. Estoy usando este código para leer el archivo de configuración de un EXE desde una DLL. No estoy seguro de si esto funciona con el archivo de configuración de ejemplo que proporcionó en su pregunta, pero debería ser un buen comienzo.

1

siguiente código le permitirá cargar contenido de XML en objetos. Según la fuente, app.config u otro archivo, use el cargador adecuado.

using System.Collections.Generic; 
using System.Xml.Serialization; 
using System.Configuration; 
using System.IO; 
using System.Xml; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var section = SectionSchool.Load(); 
     var file = FileSchool.Load("School.xml"); 
    } 
} 

cargador del archivo:

public class FileSchool 
{ 
    public static School Load(string path) 
    { 
     var encoding = System.Text.Encoding.UTF8; 
     var serializer = new XmlSerializer(typeof(School)); 

     using (var stream = new StreamReader(path, encoding, false)) 
     { 
      using (var reader = new XmlTextReader(stream)) 
      { 
       return serializer.Deserialize(reader) as School; 
      } 
     } 
    } 
} 

Sección cargador:

public class SectionSchool : ConfigurationSection 
{ 
    public School Content { get; set; } 

    protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey) 
    { 
     var serializer = new XmlSerializer(typeof(School)); // works in  4.0 
     // var serializer = new XmlSerializer(type, null, null, null, null); // works in 4.5.1 
     Content = (Schoool)serializer.Deserialize(reader); 
    } 
    public static School Load() 
    { 
     // refresh section to make sure that it will load 
     ConfigurationManager.RefreshSection("School"); 
     // will work only first time if not refreshed 
     var section = ConfigurationManager.GetSection("School") as SectionSchool; 

     if (section == null) 
      return null; 

     return section.Content; 
    } 
} 

definición de datos:

[XmlRoot("School")] 
public class School 
{ 
    [XmlAttribute("Name")] 
    public string Name { get; set; } 

    [XmlElement("Student")] 
    public List<Student> Students { get; set; } 
} 

[XmlRoot("Student")] 
public class Student 
{ 
    [XmlAttribute("Index")] 
    public int Index { get; set; } 
} 

contenido de 'aplicación.config'

<?xml version="1.0"?> 
<configuration> 

    <configSections> 
    <section name="School" type="SectionSchool, ConsoleApplication1"/> 
    </configSections> 

    <startup> 
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> 
    </startup> 

    <School Name="RT"> 
    <Student Index="1"></Student> 
    <Student /> 
    <Student /> 
    <Student /> 
    <Student Index="2"/> 
    <Student /> 
    <Student /> 
    <Student Index="3"/> 
    <Student Index="4"/> 
    </School> 

</configuration> 

contenido del archivo XML:

<?xml version="1.0" encoding="utf-8" ?> 
<School Name="RT"> 
    <Student Index="1"></Student> 
    <Student /> 
    <Student /> 
    <Student /> 
    <Student Index="2"/> 
    <Student /> 
    <Student /> 
    <Student Index="3"/> 
    <Student Index="4"/> 
</School> 

código publicado ha sido comprobado en Visual Studio 2010 (.Net 4.0). Se trabajará en .Net 4.5.1 si cambia construcción de seriliazer de

new XmlSerializer(typeof(School)) 

a

new XmlSerializer(typeof(School), null, null, null, null); 

Si se proporciona la muestra se inicia depurador fuera después trabajará con el constructor más simple, sin embargo, si inició desde VS2013 IDE con depuración, se necesitará un cambio en el constructor o bien se producirá la excepción FileNotFoundException (al menos eso fue en mi caso).

Cuestiones relacionadas