ResourceManager Clase
Definición
Representa un administrador de recursos que proporciona un acceso más cómodo a los recursos específicos de la referencia cultural en tiempo de ejecución.Represents a resource manager that provides convenient access to culture-specific resources at run time.
public ref class ResourceManager
public class ResourceManager
[System.Serializable]
public class ResourceManager
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ResourceManager
type ResourceManager = class
[<System.Serializable>]
type ResourceManager = class
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ResourceManager = class
Public Class ResourceManager
- Herencia
-
ResourceManager
- Derivado
- Atributos
Ejemplos
En el ejemplo siguiente se muestra cómo usar una referencia cultural explícita y la referencia cultural de la interfaz de usuario actual implícita para obtener recursos de cadena de un ensamblado principal y un ensamblado satélite.The following example demonstrates how to use an explicit culture and the implicit current UI culture to obtain string resources from a main assembly and a satellite assembly. Para obtener más información, consulte la sección "ubicaciones de directorio para los ensamblados satélite no instalados en la caché global de ensamblados" del tema creación de ensamblados satélite .For more information, see the "Directory Locations for Satellite Assemblies Not Installed in the Global Assembly Cache" section of the Creating Satellite Assemblies topic.
Para ejecutar este ejemplo:To run this example:
En el directorio de la aplicación, cree un archivo denominado rmc.txt que contenga las siguientes cadenas de recursos:In the app directory, create a file named rmc.txt that contains the following resource strings:
day=Friday year=2006 holiday="Cinco de Mayo"Utilice el generador de archivos de recursos para generar el archivo de recursos RMC. Resources a partir del archivo de entrada de rmc.txt como se indica a continuación:Use the Resource File Generator to generate the rmc.resources resource file from the rmc.txt input file as follows:
resgen rmc.txtCree un subdirectorio del directorio de la aplicación y asígnele el nombre "es-MX".Create a subdirectory of the app directory and name it "es-MX". Este es el nombre de la referencia cultural del ensamblado satélite que creará en los tres pasos siguientes.This is the culture name of the satellite assembly that you will create in the next three steps.
Cree un archivo denominado rmc.es-MX.txt en el directorio es-MX que contiene las siguientes cadenas de recursos:Create a file named rmc.es-MX.txt in the es-MX directory that contains the following resource strings:
day=Viernes year=2006 holiday="Cinco de Mayo"Utilice el generador de archivos de recursos para generar el archivo de recursos RMC.es-mx. Resources a partir del archivo de entrada de rmc.es-MX.txt como se indica a continuación:Use the Resource File Generator to generate the rmc.es-MX.resources resource file from the rmc.es-MX.txt input file as follows:
resgen rmc.es-MX.txtSupongamos que el nombre de archivo de este ejemplo es RMC. vb o RMC. cs.Assume that the filename for this example is rmc.vb or rmc.cs. Copie el código fuente siguiente en un archivo.Copy the following source code into a file. A continuación, compílelo e inserte el archivo de recursos del ensamblado principal, RMC. Resources, en el ensamblado ejecutable.Then compile it and embed the main assembly resource file, rmc.resources, in the executable assembly. Si usa el compilador de Visual Basic, la sintaxis es:If you are using the Visual Basic compiler, the syntax is:
vbc rmc.vb /resource:rmc.resourcesLa sintaxis correspondiente del compilador de C# es:The corresponding syntax for the C# compiler is:
csc /resource:rmc.resources rmc.csUtilice Assembly Linker para crear un ensamblado satélite.Use the Assembly Linker to create a satellite assembly. Si el nombre base de la aplicación es RMC, el nombre del ensamblado satélite debe ser rmc.resources.dll.If the base name of the app is rmc, the satellite assembly name must be rmc.resources.dll. El ensamblado satélite debe crearse en el directorio es-MX.The satellite assembly should be created in the es-MX directory. Si es-MX es el directorio actual, use este comando:If es-MX is the current directory, use this command:
al /embed:rmc.es-MX.resources /c:es-MX /out:rmc.resources.dllEjecute rmc.exe para obtener y mostrar las cadenas de recursos incrustados.Run rmc.exe to obtain and display the embedded resource strings.
using System;
using System.Resources;
using System.Reflection;
using System.Threading;
using System.Globalization;
class Example
{
public static void Main()
{
string day;
string year;
string holiday;
string celebrate = "{0} will occur on {1} in {2}.\n";
// Create a resource manager.
ResourceManager rm = new ResourceManager("rmc",
typeof(Example).Assembly);
Console.WriteLine("Obtain resources using the current UI culture.");
// Get the resource strings for the day, year, and holiday
// using the current UI culture.
day = rm.GetString("day");
year = rm.GetString("year");
holiday = rm.GetString("holiday");
Console.WriteLine(celebrate, holiday, day, year);
// Obtain the es-MX culture.
CultureInfo ci = new CultureInfo("es-MX");
Console.WriteLine("Obtain resources using the es-MX culture.");
// Get the resource strings for the day, year, and holiday
// using the specified culture.
day = rm.GetString("day", ci);
year = rm.GetString("year", ci);
holiday = rm.GetString("holiday", ci);
// ---------------------------------------------------------------
// Alternatively, comment the preceding 3 code statements and
// uncomment the following 4 code statements:
// ----------------------------------------------------------------
// Set the current UI culture to "es-MX" (Spanish-Mexico).
// Thread.CurrentThread.CurrentUICulture = ci;
// Get the resource strings for the day, year, and holiday
// using the current UI culture. Use those strings to
// display a message.
// day = rm.GetString("day");
// year = rm.GetString("year");
// holiday = rm.GetString("holiday");
// ---------------------------------------------------------------
// Regardless of the alternative that you choose, display a message
// using the retrieved resource strings.
Console.WriteLine(celebrate, holiday, day, year);
}
}
/*
This example displays the following output:
Obtain resources using the current UI culture.
"5th of May" will occur on Friday in 2006.
Obtain resources using the es-MX culture.
"Cinco de Mayo" will occur on Viernes in 2006.
*/
Imports System.Resources
Imports System.Reflection
Imports System.Threading
Imports System.Globalization
Class Example
Public Shared Sub Main()
Dim day As String
Dim year As String
Dim holiday As String
Dim celebrate As String = "{0} will occur on {1} in {2}." & vbCrLf
' Create a resource manager.
Dim rm As New ResourceManager("rmc", GetType(Example).Assembly)
Console.WriteLine("Obtain resources using the current UI culture.")
' Get the resource strings for the day, year, and holiday
' using the current UI culture.
day = rm.GetString("day")
year = rm.GetString("year")
holiday = rm.GetString("holiday")
Console.WriteLine(celebrate, holiday, day, year)
' Obtain the es-MX culture.
Dim ci As New CultureInfo("es-MX")
Console.WriteLine("Obtain resources using the es-MX culture.")
' Get the resource strings for the day, year, and holiday
' using the es-MX culture.
day = rm.GetString("day", ci)
year = rm.GetString("year", ci)
holiday = rm.GetString("holiday", ci)
' ---------------------------------------------------------------
' Alternatively, comment the preceding 3 code statements and
' uncomment the following 4 code statements:
' ----------------------------------------------------------------
' Set the current UI culture to "es-MX" (Spanish-Mexico).
' Thread.CurrentThread.CurrentUICulture = ci
' Get the resource strings for the day, year, and holiday
' using the current UI culture.
' day = rm.GetString("day")
' year = rm.GetString("year")
' holiday = rm.GetString("holiday")
' ---------------------------------------------------------------
' Regardless of the alternative that you choose, display a message
' using the retrieved resource strings.
Console.WriteLine(celebrate, holiday, day, year)
End Sub
End Class
' This example displays the following output:
'Obtain resources using the current UI culture.
'"5th of May" will occur on Friday in 2006.
'
'Obtain resources using the es-MX culture.
'"Cinco de Mayo" will occur on Viernes in 2006.
Comentarios
Importante
Llamar a métodos de esta clase con datos que no son de confianza supone un riesgo de seguridad.Calling methods from this class with untrusted data is a security risk. Llame a los métodos de esta clase solo con datos de confianza.Call the methods from this class only with trusted data. Para obtener más información, vea Data Validation (Validación de datos).For more information, see Data Validation.
La ResourceManager clase recupera recursos de un archivo. Resources binario que está incrustado en un ensamblado o desde un archivo. Resources independiente.The ResourceManager class retrieves resources from a binary .resources file that is embedded in an assembly or from a standalone .resources file. Si una aplicación se ha localizado y los recursos localizados se han implementado en ensamblados satélite, busca recursos específicos de la referencia cultural, proporciona reserva de recursos cuando no existe un recurso localizado y admite la serialización de recursos.If an app has been localized and localized resources have been deployed in satellite assemblies, it looks up culture-specific resources, provides resource fallback when a localized resource does not exist, and supports resource serialization.
Para obtener más información sobre cómo crear y administrar recursos en aplicaciones de escritorio y aplicaciones de la tienda Windows 8. x, vea las siguientes secciones:For more information about creating and managing resources in desktop apps and Windows 8.x Store apps, see the following sections:
Aplicaciones de escritorioDesktop Apps
Crear instancias de un objeto ResourceManagerInstantiating a ResourceManager Object
Recursos de ResourceManager y Culture-SpecificResourceManager and Culture-Specific Resources
Recuperar recursos de aplicaciones de escritorioRetrieving Resources
<satelliteassemblies> Nodo del archivo de configuración<satelliteassemblies> Configuration File Node
Aplicaciones de escritorioDesktop Apps
En el caso de las aplicaciones de escritorio, la ResourceManager clase recupera los recursos de los archivos de recursos binarios (. Resources).For desktop apps, the ResourceManager class retrieves resources from binary resource (.resources) files. Normalmente, un compilador de lenguaje o Assembly Linker (AL.exe) inserta estos archivos de recursos en un ensamblado.Typically, a language compiler or the Assembly Linker (AL.exe) embeds these resource files in an assembly. También puede utilizar un ResourceManager objeto para recuperar recursos directamente de un archivo. Resources que no está incrustado en un ensamblado, llamando al CreateFileBasedResourceManager método.You can also use a ResourceManager object to retrieve resources directly from a .resources file that is not embedded in an assembly, by calling the CreateFileBasedResourceManager method.
Precaución
El uso de archivos. resources independientes en una aplicación ASP.NET interrumpirá la implementación de XCOPY, ya que los recursos permanecen bloqueados hasta que el método los libera explícitamente ReleaseAllResources .Using standalone .resources files in an ASP.NET app will break XCOPY deployment, because the resources remain locked until they are explicitly released by the ReleaseAllResources method. Si desea implementar recursos con las aplicaciones de ASP.NET, debe compilar los archivos. Resources en ensamblados satélite.If you want to deploy resources with your ASP.NET apps, you should compile your .resources files into satellite assemblies.
En una aplicación basada en recursos, un archivo. Resources contiene los recursos de la referencia cultural predeterminada cuyos recursos se usan si no se pueden encontrar recursos específicos de la referencia cultural.In a resource-based app, one .resources file contains the resources of the default culture whose resources are used if no culture-specific resources can be found. Por ejemplo, si la referencia cultural predeterminada de una aplicación es el inglés (en), los recursos del idioma inglés se usan siempre que no se encuentran recursos localizados para una referencia cultural concreta, como inglés (Estados Unidos) (en-US) o francés (Francia) (fr-FR).For example, if an app's default culture is English (en), the English language resources are used whenever localized resources cannot be found for a specific culture, such as English (United States) (en-US) or French (France) (fr-FR). Normalmente, los recursos de la referencia cultural predeterminada se incrustan en el ensamblado de la aplicación principal y los recursos para otras referencias culturales localizadas se incrustan en los ensamblados satélite.Typically, the resources for the default culture are embedded in the main app assembly, and resources for other localized cultures are embedded in satellite assemblies. Los ensamblados satélite solo contienen recursos.Satellite assemblies contain only resources. Tienen el mismo nombre de archivo raíz que el ensamblado principal y una extensión de .resources.dll.They have the same root file name as the main assembly and an extension of .resources.dll. En el caso de las aplicaciones cuyos ensamblados no están registrados en la caché global de ensamblados, los ensamblados satélite se almacenan en un subdirectorio de la aplicación cuyo nombre corresponde a la referencia cultural del ensamblado.For apps whose assemblies are not registered in the global assembly cache, satellite assemblies are stored in an app subdirectory whose name corresponds to the assembly's culture.
Crear recursosCreating Resources
Al desarrollar una aplicación basada en recursos, se almacena la información de recursos en archivos de texto (archivos que tienen una extensión. txt o. restext) o archivos XML (archivos que tienen una extensión. resx).When you develop a resource-based app, you store resource information in text files (files that have a .txt or .restext extension) or XML files (files that have a .resx extension). A continuación, compile los archivos de texto o XML con el generador de archivos de recursos (Resgen.exe) para crear un archivo. Resources binario.You then compile the text or XML files with the Resource File Generator (Resgen.exe) to create a binary .resources file. Después, puede insertar el archivo. Resources resultante en una biblioteca ejecutable o mediante una opción del compilador como /resources para los compiladores de C# y Visual Basic, o puede incrustarlo en un ensamblado satélite mediante Assembly Linker (AI.exe).You can then embed the resulting .resources file in an executable or library by using a compiler option such as /resources for the C# and Visual Basic compilers, or you can embed it in a satellite assembly by using the Assembly Linker (AI.exe). Si incluye un archivo. resx en el proyecto de Visual Studio, Visual Studio controla la compilación y la incrustación de los recursos predeterminados y localizados automáticamente como parte del proceso de compilación.If you include a .resx file in your Visual Studio project, Visual Studio handles the compilation and embedding of default and localized resources automatically as part of the build process.
Idealmente, debe crear recursos para cada idioma que admita la aplicación, o al menos para un subconjunto significativo de cada idioma.Ideally, you should create resources for every language your app supports, or at least for a meaningful subset of each language. Los nombres de archivo. Resources binarios siguen la Convención de nomenclatura basename. CultureName. Resources, donde basename es el nombre de la aplicación o el nombre de una clase, según el nivel de detalle que desee.The binary .resources file names follow the naming convention basename.cultureName.resources, where basename is the name of the app or the name of a class, depending on the level of detail you want. La CultureInfo.Name propiedad se utiliza para determinar CultureName.The CultureInfo.Name property is used to determine cultureName. Un recurso de la referencia cultural predeterminada de la aplicación debe tener el nombre basename. Resources.A resource for the app's default culture should be named basename.resources.
Por ejemplo, supongamos que un ensamblado tiene varios recursos en un archivo de recursos que tiene el nombre base MyResources.For example, suppose that an assembly has several resources in a resource file that has the base name MyResources. Estos archivos de recursos deben tener nombres como MyResources. ja-JP. Resources para la referencia cultural de Japón (japonés), MyResources. de. Resources para la referencia cultural alemana, MyResources. ZH-CHS. Resources para la referencia cultural de chino simplificado y MyResources.fr-is. Resources para la referencia cultural de francés (Bélgica).These resource files should have names such as MyResources.ja-JP.resources for the Japan (Japanese) culture, MyResources.de.resources for the German culture, MyResources.zh-CHS.resources for the simplified Chinese culture, and MyResources.fr-BE.resources for the French (Belgium) culture. El archivo de recursos predeterminado debe denominarse MyResources. Resources.The default resource file should be named MyResources.resources. Normalmente, los archivos de recursos específicos de la referencia cultural se empaquetan en ensamblados satélite para cada referencia cultural.The culture-specific resource files are commonly packaged in satellite assemblies for each culture. El archivo de recursos predeterminado debe estar incrustado en el ensamblado principal de la aplicación.The default resource file should be embedded in the app's main assembly.
Tenga en cuenta que Assembly Linker permite marcar los recursos como privados, pero siempre debe marcarlos como públicos para que otros ensamblados puedan tener acceso a ellos.Note that Assembly Linker allows resources to be marked as private, but you should always mark them as public so they can be accessed by other assemblies. (Dado que un ensamblado satélite no contiene ningún código, los recursos marcados como privados no están disponibles para la aplicación a través de ningún mecanismo).(Because a satellite assembly contains no code, resources that are marked as private are unavailable to your app through any mechanism.)
Para obtener más información sobre la creación, el empaquetado y la implementación de recursos, vea los artículos crear archivos de recursos, crear ensamblados satélitey empaquetar e implementar recursos.For more information about creating, packaging, and deploying resources, see the articles Creating Resource Files, Creating Satellite Assemblies, and Packaging and Deploying Resources.
Crear instancias de un objeto ResourceManagerInstantiating a ResourceManager Object
Crea una instancia ResourceManager de un objeto que recupera recursos de un archivo. Resources incrustado llamando a una de sus sobrecargas del constructor de clase.You instantiate a ResourceManager object that retrieves resources from an embedded .resources file by calling one of its class constructor overloads. Esto acopla estrechamente un ResourceManager objeto con un archivo. Resources determinado y con los archivos. Resources localizados asociados en ensamblados satélite.This tightly couples a ResourceManager object with a particular .resources file and with any associated localized .resources files in satellite assemblies.
Los dos constructores más comúnmente denominados son:The two most commonly called constructors are:
ResourceManager(String, Assembly) busca recursos en función de dos fragmentos de información que proporcione: el nombre base del archivo. Resources y el ensamblado en el que reside el archivo default. Resources.ResourceManager(String, Assembly) looks up resources based on two pieces of information that you supply: the base name of the .resources file, and the assembly in which the default .resources file resides. El nombre base incluye el espacio de nombres y el nombre raíz del archivo. Resources, sin su referencia cultural o extensión.The base name includes the namespace and root name of the .resources file, without its culture or extension. Tenga en cuenta que los archivos. Resources que se compilan desde la línea de comandos normalmente no incluyen un nombre de espacio de nombres, mientras que los archivos. Resources que se crean en el entorno de Visual Studio.Note that .resources files that are compiled from the command line typically do not include a namespace name, whereas .resources files that are created in the Visual Studio environment do. Por ejemplo, si un archivo de recursos se denomina mycompany. StringResources. Resources y ResourceManager se llama al constructor desde un método estático denominado
Example.Main, el código siguiente crea una instancia de un ResourceManager objeto que puede recuperar recursos del archivo. Resources:For example, if a resource file is named MyCompany.StringResources.resources and the ResourceManager constructor is called from a static method namedExample.Main, the following code instantiates a ResourceManager object that can retrieve resources from the .resources file:ResourceManager rm = new ResourceManager("MyCompany.StringResources", typeof(Example).Assembly);Dim rm As New ResourceManager("MyCompany.StringResources", GetType(Example).Assembly)ResourceManager(Type) busca recursos en los ensamblados satélite basándose en la información de un objeto de tipo.ResourceManager(Type) looks up resources in satellite assemblies based on information from a type object. El nombre completo del tipo corresponde al nombre base del archivo. Resources sin su extensión de nombre de archivo.The type's fully qualified name corresponds to the base name of the .resources file without its file name extension. En las aplicaciones de escritorio que se crean mediante el diseñador de recursos de Visual Studio, Visual Studio crea una clase contenedora cuyo nombre completo es el mismo que el nombre raíz del archivo. Resources.In desktop apps that are created by using the Visual Studio Resource Designer, Visual Studio creates a wrapper class whose fully qualified name is the same as the root name of the .resources file. Por ejemplo, si un archivo de recursos se denomina mycompany. StringResources. Resources y hay una clase contenedora denominada
MyCompany.StringResources, el código siguiente crea una instancia de un ResourceManager objeto que puede recuperar recursos del archivo. Resources:For example, if a resource file is named MyCompany.StringResources.resources and there is a wrapper class namedMyCompany.StringResources, the following code instantiates a ResourceManager object that can retrieve resources from the .resources file:ResourceManager rm = new ResourceManager(typeof(MyCompany.StringResources));Dim rm As New ResourceManager(GetType(MyCompany.StringResources))
Si no se encuentran los recursos adecuados, la llamada al constructor crea un ResourceManager objeto válido.If the appropriate resources cannot be found, the constructor call creates a valid ResourceManager object. Sin embargo, el intento de recuperar un recurso produce una MissingManifestResourceException excepción.However, the attempt to retrieve a resource throws a MissingManifestResourceException exception. Para obtener información sobre cómo tratar la excepción, consulte la sección control de excepciones MissingManifestResourceException y MissingSatelliteAssembly más adelante en este artículo.For information about dealing with the exception, see the Handling MissingManifestResourceException and MissingSatelliteAssembly Exceptions section later in this article.
En el ejemplo siguiente se muestra cómo crear una instancia de un ResourceManager objeto.The following example shows how to instantiate a ResourceManager object. Contiene el código fuente de un archivo ejecutable denominado ShowTime.exe.It contains the source code for an executable named ShowTime.exe. También incluye el siguiente archivo de texto denominado Strings.txt que contiene un recurso de cadena único TimeHeader :It also includes the following text file named Strings.txt that contains a single string resource, TimeHeader:
TimeHeader=The current time is
Puede usar un archivo por lotes para generar el archivo de recursos e insertarlo en el archivo ejecutable.You can use a batch file to generate the resource file and embed it into the executable. Este es el archivo por lotes para generar un archivo ejecutable mediante el compilador de C#:Here's the batch file to generate an executable by using the C# compiler:
resgen strings.txt
csc ShowTime.cs /resource:strings.resources
Para el compilador de Visual Basic, puede usar el siguiente archivo por lotes:For the Visual Basic compiler, you can use the following batch file:
resgen strings.txt
vbc ShowTime.vb /resource:strings.resources
using System;
using System.Resources;
public class Example
{
public static void Main()
{
ResourceManager rm = new ResourceManager("Strings",
typeof(Example).Assembly);
string timeString = rm.GetString("TimeHeader");
Console.WriteLine("{0} {1:T}", timeString, DateTime.Now);
}
}
// The example displays output like the following:
// The current time is 2:03:14 PM
Imports System.Resources
Module Example
Public Sub Main()
Dim rm As New ResourceManager("Strings", GetType(Example).Assembly)
Dim timeString As String = rm.GetString("TimeHeader")
Console.WriteLine("{0} {1:T}", timeString, Date.Now)
End Sub
End Module
' The example displays output similar to the following:
' The current time is 2:03:14 PM
Recursos de ResourceManager y Culture-SpecificResourceManager and Culture-Specific Resources
Una aplicación localizada requiere la implementación de recursos, como se describe en el artículo empaquetado e implementación de recursos.A localized app requires resources to be deployed, as discussed in the article Packaging and Deploying Resources. Si los ensamblados están configurados correctamente, el administrador de recursos determina qué recursos se van a recuperar en función de la propiedad del subproceso actual Thread.CurrentUICulture .If the assemblies are properly configured, the resource manager determines which resources to retrieve based on the current thread's Thread.CurrentUICulture property. (Esa propiedad también devuelve la referencia cultural de la interfaz de usuario del subproceso actual). Por ejemplo, si una aplicación se compila con los recursos de idioma inglés predeterminados en el ensamblado principal y con los recursos de idioma francés y ruso en dos ensamblados satélite, y la Thread.CurrentUICulture propiedad se establece en fr-fr, el administrador de recursos recupera los recursos en francés.(That property also returns the current thread's UI culture.) For example, if an app is compiled with default English language resources in the main assembly and with French and Russian language resources in two satellite assemblies, and the Thread.CurrentUICulture property is set to fr-FR, the resource manager retrieves the French resources.
Puede establecer la CurrentUICulture propiedad de forma explícita o implícita.You can set the CurrentUICulture property explicitly or implicitly. La forma en que se establece determina cómo el ResourceManager objeto recupera los recursos en función de la referencia cultural:The way you set it determines how the ResourceManager object retrieves resources based on culture:
Si establece explícitamente la Thread.CurrentUICulture propiedad en una referencia cultural concreta, el administrador de recursos siempre recupera los recursos para esa referencia cultural, independientemente del explorador del usuario o del idioma del sistema operativo.If you explicitly set the Thread.CurrentUICulture property to a specific culture, the resource manager always retrieves the resources for that culture, regardless of the user's browser or operating system language. Considere una aplicación que está compilada con los recursos de idioma inglés predeterminados y tres ensamblados satélite que contienen recursos para inglés (Estados Unidos), francés (Francia) y ruso (Rusia).Consider an app that is compiled with default English language resources and three satellite assemblies that contain resources for English (United States), French (France), and Russian (Russia). Si la CurrentUICulture propiedad está establecida en fr-fr, el ResourceManager objeto siempre recupera los recursos en francés (Francia), incluso si el idioma del sistema operativo del usuario no es francés.If the CurrentUICulture property is set to fr-FR, the ResourceManager object always retrieves the French (France) resources, even if the user's operating system language is not French. Asegúrese de que este es el comportamiento deseado antes de establecer la propiedad explícitamente.Make sure that this is the desired behavior before you set the property explicitly.
En ASP.NET Apps, debe establecer la Thread.CurrentUICulture propiedad explícitamente, porque es improbable que la configuración del servidor coincida con las solicitudes de cliente entrantes.In ASP.NET apps, you must set the Thread.CurrentUICulture property explicitly, because it is unlikely that the setting on the server will match incoming client requests. Una aplicación ASP.NET puede establecer la Thread.CurrentUICulture propiedad explícitamente en el idioma de aceptación del explorador del usuario.An ASP.NET app can set the Thread.CurrentUICulture property explicitly to the user's browser accept language.
Establecer explícitamente la Thread.CurrentUICulture propiedad define la referencia cultural de la interfaz de usuario actual para ese subproceso.Explicitly setting the Thread.CurrentUICulture property defines the current UI culture for that thread. No afecta a la referencia cultural actual de la interfaz de usuario de otros subprocesos de una aplicación.It does not affect the current UI culture of any other threads in an app.
Puede establecer la referencia cultural de la interfaz de usuario de todos los subprocesos de un dominio de aplicación mediante la asignación de un CultureInfo objeto que representa esa referencia cultural a la CultureInfo.DefaultThreadCurrentUICulture propiedad estática.You can set the UI culture of all threads in an app domain by assigning a CultureInfo object that represents that culture to the static CultureInfo.DefaultThreadCurrentUICulture property.
Si no establece explícitamente la referencia cultural de la interfaz de usuario actual y no define una referencia cultural predeterminada para el dominio de aplicación actual, la CultureInfo.CurrentUICulture propiedad se establece implícitamente mediante la función de Windows
GetUserDefaultUILanguage.If you do not explicitly set the current UI culture and you do not define a default culture for the current app domain, the CultureInfo.CurrentUICulture property is set implicitly by the WindowsGetUserDefaultUILanguagefunction. Esta función se proporciona mediante la interfaz de usuario multilingüe (MUI), que permite al usuario establecer el idioma predeterminado.This function is provided by the Multilingual User Interface (MUI), which enables the user to set the default language. Si el usuario no establece el idioma de la interfaz de usuario, el valor predeterminado es el idioma instalado por el sistema, que es el idioma de los recursos del sistema operativo.If the UI language is not set by the user, it defaults to the system-installed language, which is the language of operating system resources.
En el siguiente ejemplo simple "Hello World" se establece explícitamente la referencia cultural de la interfaz de usuario actual.The following simple "Hello world" example sets the current UI culture explicitly. Contiene recursos para tres referencias culturales: Inglés (Estados Unidos) o en-US, francés (Francia) o fr-FR, y ruso (Rusia) o ru-RU.It contains resources for three cultures: English (United States) or en-US, French (France) or fr-FR, and Russian (Russia) or ru-RU. Los recursos en-US se encuentran en un archivo de texto denominado Greetings.txt:The en-US resources are contained in a text file named Greetings.txt:
HelloString=Hello world!
Los recursos de fr-FR se encuentran en un archivo de texto denominado Greetings.fr-FR.txt:The fr-FR resources are contained in a text file named Greetings.fr-FR.txt:
HelloString=Salut tout le monde!
Los recursos ru-RU se encuentran en un archivo de texto denominado Greetings.ru-RU.txt:The ru-RU resources are contained in a text file named Greetings.ru-RU.txt:
HelloString=Всем привет!
Este es el código fuente del ejemplo (example. VB para la versión de Visual Basic o example. CS para la versión de C#):Here's the source code for the example (Example.vb for the Visual Basic version or Example.cs for the C# version):
using System;
using System.Globalization;
using System.Resources;
using System.Threading;
public class Example
{
public static void Main()
{
// Create array of supported cultures
string[] cultures = {"en-CA", "en-US", "fr-FR", "ru-RU" };
Random rnd = new Random();
int cultureNdx = rnd.Next(0, cultures.Length);
CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
ResourceManager rm = new ResourceManager("Greetings", typeof(Example).Assembly);
try {
CultureInfo newCulture = new CultureInfo(cultures[cultureNdx]);
Thread.CurrentThread.CurrentCulture = newCulture;
Thread.CurrentThread.CurrentUICulture = newCulture;
string greeting = String.Format("The current culture is {0}.\n{1}",
Thread.CurrentThread.CurrentUICulture.Name,
rm.GetString("HelloString"));
Console.WriteLine(greeting);
}
catch (CultureNotFoundException e) {
Console.WriteLine("Unable to instantiate culture {0}", e.InvalidCultureName);
}
finally {
Thread.CurrentThread.CurrentCulture = originalCulture;
Thread.CurrentThread.CurrentUICulture = originalCulture;
}
}
}
// The example displays output like the following:
// The current culture is ru-RU.
// Всем привет!
Imports System.Globalization
Imports System.Resources
Imports System.Threading
Module Example
Sub Main()
' Create array of supported cultures
Dim cultures() As String = {"en-CA", "en-US", "fr-FR", "ru-RU" }
Dim rnd As New Random()
Dim cultureNdx As Integer = rnd.Next(0, cultures.Length)
Dim originalCulture As CultureInfo = Thread.CurrentThread.CurrentCulture
Dim rm As New ResourceManager("Greetings", GetType(Example).Assembly)
Try
Dim newCulture As New CultureInfo(cultures(cultureNdx))
Thread.CurrentThread.CurrentCulture = newCulture
Thread.CurrentThread.CurrentUICulture = newCulture
Dim greeting As String = String.Format("The current culture is {0}.{1}{2}",
Thread.CurrentThread.CurrentUICulture.Name,
vbCrLf, rm.GetString("HelloString"))
Console.WriteLine(greeting)
Catch e As CultureNotFoundException
Console.WriteLine("Unable to instantiate culture {0}", e.InvalidCultureName)
Finally
Thread.CurrentThread.CurrentCulture = originalCulture
Thread.CurrentThread.CurrentUICulture = originalCulture
End Try
End Sub
End Module
' The example displays output like the following:
' The current culture is ru-RU.
' Всем привет!
Para compilar este ejemplo, cree un archivo por lotes (. bat) que contenga los siguientes comandos y ejecútelo desde el símbolo del sistema.To compile this example, create a batch (.bat) file that contains the following commands and run it from the command prompt. Si usa C#, especifique csc en lugar de vbc y Example.cs en lugar de Example.vb .If you're using C#, specify csc instead of vbc and Example.cs instead of Example.vb.
resgen Greetings.txt
vbc Example.vb /resource:Greetings.resources
resgen Greetings.fr-FR.txt
Md fr-FR
al /embed:Greetings.fr-FR.resources /culture:fr-FR /out:fr-FR\Example.resources.dll
resgen Greetings.ru-RU.txt
Md ru-RU
al /embed:Greetings.ru-RU.resources /culture:ru-RU /out:ru-RU\Example.resources.dll
Recuperar recursosRetrieving Resources
Se llama GetObject(String) a los GetString(String) métodos y para tener acceso a un recurso específico.You call the GetObject(String) and GetString(String) methods to access a specific resource. También puede llamar al GetStream(String) método para recuperar recursos que no son de cadena como una matriz de bytes.You can also call the GetStream(String) method to retrieve non-string resources as a byte array. De forma predeterminada, en una aplicación que tiene recursos localizados, estos métodos devuelven el recurso para la referencia cultural determinada por la referencia cultural de la interfaz de usuario actual del subproceso que realizó la llamada.By default, in an app that has localized resources, these methods return the resource for the culture determined by the current UI culture of the thread that made the call. Vea la sección anterior, recursos de ResourceManager y Culture-Specificpara obtener más información sobre cómo se define la referencia cultural de la interfaz de usuario actual de un subproceso.See the previous section, ResourceManager and Culture-Specific Resources, for more information about how the current UI culture of a thread is defined. Si el administrador de recursos no puede encontrar el recurso para la referencia cultural de la interfaz de usuario del subproceso actual, usa un proceso de reserva para recuperar el recurso especificado.If the resource manager cannot find the resource for the current thread's UI culture, it uses a fallback process to retrieve the specified resource. Si el administrador de recursos no puede encontrar recursos localizados, usa los recursos de la referencia cultural predeterminada.If the resource manager cannot find any localized resources, it uses the resources of the default culture. Para obtener más información sobre las reglas de reserva de recursos, consulte la sección "proceso de reserva de recursos" del artículo empaquetar e implementar recursos.For more information about resource fallback rules, see the "Resource Fallback Process" section of the article Packaging and Deploying Resources.
Nota
Si no se encuentra el archivo. Resources especificado en el ResourceManager constructor de clase, el intento de recuperar un recurso produce una MissingManifestResourceException MissingSatelliteAssemblyException excepción o.If the .resources file specified in the ResourceManager class constructor cannot be found, the attempt to retrieve a resource throws a MissingManifestResourceException or MissingSatelliteAssemblyException exception. Para obtener información sobre cómo tratar la excepción, vea la sección control de excepciones MissingManifestResourceException y MissingSatelliteAssemblyException más adelante en este tema.For information about dealing with the exception, see the Handling MissingManifestResourceException and MissingSatelliteAssemblyException Exceptions section later in this topic.
En el ejemplo siguiente se usa el GetString método para recuperar los recursos específicos de la referencia cultural.The following example uses the GetString method to retrieve culture-specific resources. Consta de recursos compilados a partir de archivos. txt para las referencias culturales de inglés (en), francés (Francia) (fr-FR) y ruso (Rusia) (ru-RU).It consists of resources compiled from .txt files for the English (en), French (France) (fr-FR), and Russian (Russia) (ru-RU) cultures. En el ejemplo se cambia la referencia cultural actual y la referencia cultural actual de la interfaz de usuario a Inglés (Estados Unidos), francés (Francia), Ruso (Rusia) y sueco (Suecia).The example changes the current culture and current UI culture to English (United States), French (France), Russian (Russia), and Swedish (Sweden). A continuación, llama al GetString método para recuperar la cadena localizada, que se muestra junto con el día y el mes actuales.It then calls the GetString method to retrieve the localized string, which it displays along with the current day and month. Observe que la salida muestra la cadena localizada adecuada, excepto cuando la referencia cultural de la interfaz de usuario actual es sueco (Suecia).Notice that the output displays the appropriate localized string except when the current UI culture is Swedish (Sweden). Dado que los recursos de idioma sueco no están disponibles, la aplicación usa en su lugar los recursos de la referencia cultural predeterminada, que es el inglés.Because Swedish language resources are unavailable, the app instead uses the resources of the default culture, which is English.
El ejemplo requiere los archivos de recursos basados en texto que se enumeran en la tabla siguiente.The example requires the text-based resource files listed in following table. Cada tiene un recurso de cadena único denominado DateStart .Each has a single string resource named DateStart.
| cultureCulture | Nombre de archivoFile name | Nombre del recursoResource name | Valor del recursoResource value |
|---|---|---|---|
| en-USen-US | DateStrings.txtDateStrings.txt | DateStart |
Hoy esToday is |
| fr-FRfr-FR | DateStrings.fr-FR.txtDateStrings.fr-FR.txt | DateStart |
Aujourd'hui, c'est leAujourd'hui, c'est le |
| ru-RUru-RU | DateStrings.ru-RU.txtDateStrings.ru-RU.txt | DateStart |
СегодняСегодня |
Este es el código fuente del ejemplo (ShowDate. VB para la versión de Visual Basic o ShowDate. CS para la versión de C# del código).Here's the source code for the example (ShowDate.vb for the Visual Basic version or ShowDate.cs for the C# version of the code).
using System;
using System.Globalization;
using System.Resources;
using System.Threading;
[assembly:NeutralResourcesLanguage("en")]
public class Example
{
public static void Main()
{
string[] cultureNames = { "en-US", "fr-FR", "ru-RU", "sv-SE" };
ResourceManager rm = new ResourceManager("DateStrings",
typeof(Example).Assembly);
foreach (var cultureName in cultureNames) {
CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
Console.WriteLine("Current UI Culture: {0}",
CultureInfo.CurrentUICulture.Name);
string dateString = rm.GetString("DateStart");
Console.WriteLine("{0} {1:M}.\n", dateString, DateTime.Now);
}
}
}
// The example displays output similar to the following:
// Current UI Culture: en-US
// Today is February 03.
//
// Current UI Culture: fr-FR
// Aujourd'hui, c'est le 3 février
//
// Current UI Culture: ru-RU
// Сегодня февраля 03.
//
// Current UI Culture: sv-SE
// Today is den 3 februari.
Imports System.Globalization
Imports System.Resources
Imports System.Threading
<Assembly:NeutralResourcesLanguage("en")>
Module Example
Public Sub Main()
Dim cultureNames() As String = { "en-US", "fr-FR", "ru-RU", "sv-SE" }
Dim rm As New ResourceManager("DateStrings",
GetType(Example).Assembly)
For Each cultureName In cultureNames
Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture(cultureName)
Thread.CurrentThread.CurrentCulture = culture
Thread.CurrentThread.CurrentUICulture = culture
Console.WriteLine("Current UI Culture: {0}",
CultureInfo.CurrentUICulture.Name)
Dim dateString As String = rm.GetString("DateStart")
Console.WriteLine("{0} {1:M}.", dateString, Date.Now)
Console.WriteLine()
Next
End Sub
End Module
' The example displays output similar to the following:
' Current UI Culture: en-US
' Today is February 03.
'
' Current UI Culture: fr-FR
' Aujourd'hui, c'est le 3 février
'
' Current UI Culture: ru-RU
' Сегодня февраля 03.
'
' Current UI Culture: sv-SE
' Today is den 3 februari.
Para compilar este ejemplo, cree un archivo por lotes que contenga los siguientes comandos y ejecútelo desde el símbolo del sistema.To compile this example, create a batch file that contains the following commands and run it from the command prompt. Si usa C#, especifique csc en lugar de vbc y showdate.cs en lugar de showdate.vb .If you're using C#, specify csc instead of vbc and showdate.cs instead of showdate.vb.
resgen DateStrings.txt
vbc showdate.vb /resource:DateStrings.resources
md fr-FR
resgen DateStrings.fr-FR.txt
al /out:fr-FR\Showdate.resources.dll /culture:fr-FR /embed:DateStrings.fr-FR.resources
md ru-RU
resgen DateStrings.ru-RU.txt
al /out:ru-RU\Showdate.resources.dll /culture:ru-RU /embed:DateStrings.ru-RU.resources
Hay dos maneras de recuperar los recursos de una referencia cultural específica que no sea la referencia cultural de la interfaz de usuario actual:There are two ways to retrieve the resources of a specific culture other than the current UI culture:
Puede llamar al GetString(String, CultureInfo) método, GetObject(String, CultureInfo) o GetStream(String, CultureInfo) para recuperar un recurso para una referencia cultural concreta.You can call the GetString(String, CultureInfo), GetObject(String, CultureInfo), or GetStream(String, CultureInfo) method to retrieve a resource for a specific culture. Si no se encuentra un recurso localizado, el administrador de recursos usa el proceso de reserva de recursos para buscar un recurso adecuado.If a localized resource cannot be found, the resource manager uses the resource fallback process to locate an appropriate resource.
Puede llamar al GetResourceSet método para obtener un ResourceSet objeto que represente los recursos de una referencia cultural determinada.You can call the GetResourceSet method to obtain a ResourceSet object that represents the resources for a particular culture. En la llamada al método, puede determinar si el administrador de recursos sondea las referencias culturales principales si no puede encontrar recursos localizados o si simplemente recurre a los recursos de la referencia cultural predeterminada.In the method call, you can determine whether the resource manager probes for parent cultures if it is unable to find localized resources, or whether it simply falls back to the resources of the default culture. A continuación, puede utilizar los ResourceSet métodos para tener acceso a los recursos (adaptados a esa referencia cultural) por nombre, o para enumerar los recursos del conjunto.You can then use the ResourceSet methods to access the resources (localized for that culture) by name, or to enumerate the resources in the set.
Controlar las excepciones MissingManifestResourceException y MissingSatelliteAssemblyExceptionHandling MissingManifestResourceException and MissingSatelliteAssemblyException Exceptions
Si intenta recuperar un recurso específico, pero el administrador de recursos no puede encontrar ese recurso y no se ha definido ninguna referencia cultural predeterminada o no se encuentran los recursos de la referencia cultural predeterminada, el administrador de recursos produce una MissingManifestResourceException excepción si espera encontrar los recursos en el ensamblado principal o en MissingSatelliteAssemblyException si espera encontrar los recursos en un ensamblado satélite.If you try to retrieve a specific resource, but the resource manager cannot find that resource and either no default culture has been defined or the resources of the default culture cannot be located, the resource manager throws a MissingManifestResourceException exception if it expects to find the resources in the main assembly or a MissingSatelliteAssemblyException if it expects to find the resources in a satellite assembly. Tenga en cuenta que la excepción se produce cuando se llama a un método de recuperación de recursos como GetString o GetObject , y no al crear una instancia de un ResourceManager objeto.Note that the exception is thrown when you call a resource retrieval method such as GetString or GetObject, and not when you instantiate a ResourceManager object.
Normalmente, la excepción se produce en las siguientes condiciones:The exception is typically thrown under the following conditions:
No existe el archivo de recursos o ensamblado satélite adecuado.The appropriate resource file or satellite assembly does not exist. Si el administrador de recursos espera que los recursos predeterminados de la aplicación se incrusten en el ensamblado de la aplicación principal, están ausentes.If the resource manager expects the app's default resources to be embedded in the main app assembly, they are absent. Si el NeutralResourcesLanguageAttribute atributo indica que los recursos predeterminados de la aplicación residen en un ensamblado satélite, no se puede encontrar ese ensamblado.If the NeutralResourcesLanguageAttribute attribute indicates that the app's default resources reside in a satellite assembly, that assembly cannot be found. Al compilar la aplicación, asegúrese de que los recursos están incrustados en el ensamblado principal o de que se genera el ensamblado satélite necesario y se le asigna un nombre adecuado.When you compile your app, make sure that resources are embedded in the main assembly or that the necessary satellite assembly is generated and is named appropriately. Su nombre debe tener el formato appName.resources.dll y debe estar ubicado en un directorio con el nombre de la referencia cultural cuyos recursos contiene.Its name should take the form appName.resources.dll, and it should be located in a directory named after the culture whose resources it contains.
La aplicación no tiene definida una referencia cultural predeterminada o neutra.Your app doesn't have a default or neutral culture defined. Agregue el NeutralResourcesLanguageAttribute atributo a un archivo de código fuente o al archivo de información del proyecto (AssemblyInfo. VB para una aplicación Visual Basic o AssemblyInfo. CS para un archivo de aplicación de C#).Add the NeutralResourcesLanguageAttribute attribute to a source code file or to the project information file (AssemblyInfo.vb for a Visual Basic app or AssemblyInfo.cs for a C# app) file.
El
baseNameparámetro del ResourceManager(String, Assembly) constructor no especifica el nombre de un archivo. Resources.ThebaseNameparameter in the ResourceManager(String, Assembly) constructor does not specify the name of a .resources file. El nombre debe incluir el espacio de nombres completo del archivo de recursos, pero no su extensión de nombre de archivo.The name should include the resource file's fully qualified namespace but not its file name extension. Normalmente, los archivos de recursos que se crean en Visual Studio incluyen nombres de espacios de nombres, pero los archivos de recursos que se crean y se compilan en el símbolo del sistema no lo hacen.Typically, resource files that are created in Visual Studio include namespace names, but resource files that are created and compiled at the command prompt do not. Puede determinar los nombres de los archivos. Resources incrustados compilando y ejecutando la siguiente utilidad.You can determine the names of embedded .resources files by compiling and running the following utility. Se trata de una aplicación de consola que acepta el nombre de un ensamblado principal o un ensamblado satélite como parámetro de línea de comandos.This is a console app that accepts the name of a main assembly or satellite assembly as a command-line parameter. Muestra las cadenas que se deben proporcionar comobaseNameparámetro para que el administrador de recursos pueda identificar correctamente el recurso.It displays the strings that should be provided as thebaseNameparameter so that the resource manager can correctly identify the resource.using System; using System.IO; using System.Reflection; using System.Resources; public class Example { public static void Main() { if (Environment.GetCommandLineArgs().Length == 1) { Console.WriteLine("No filename."); return; } string filename = Environment.GetCommandLineArgs()[1].Trim(); // Check whether the file exists. if (! File.Exists(filename)) { Console.WriteLine("{0} does not exist.", filename); return; } // Try to load the assembly. Assembly assem = Assembly.LoadFrom(filename); Console.WriteLine("File: {0}", filename); // Enumerate the resource files. string[] resNames = assem.GetManifestResourceNames(); if (resNames.Length == 0) Console.WriteLine(" No resources found."); foreach (var resName in resNames) Console.WriteLine(" Resource: {0}", resName.Replace(".resources", "")); Console.WriteLine(); } }Imports System.IO Imports System.Reflection Imports System.Resources Module Example Public Sub Main() If Environment.GetCommandLineArgs.Length = 1 Then Console.WriteLine("No filename.") Exit Sub End If Dim filename As String = Environment.GetCommandLineArgs(1).Trim() ' Check whether the file exists. If Not File.Exists(filename) Then Console.WriteLine("{0} does not exist.", filename) Exit Sub End If ' Try to load the assembly. Dim assem As Assembly = Assembly.LoadFrom(filename) Console.WriteLine("File: {0}", filename) ' Enumerate the resource files. Dim resNames() As String = assem.GetManifestResourceNames() If resNames.Length = 0 Then Console.WriteLine(" No resources found.") End If For Each resName In resNames Console.WriteLine(" Resource: {0}", resName.Replace(".resources", "")) Next Console.WriteLine() End Sub End Module
Si va a cambiar explícitamente la referencia cultural actual de la aplicación, también debe recordar que el administrador de recursos recupera un conjunto de recursos según el valor de la CultureInfo.CurrentUICulture propiedad, y no la CultureInfo.CurrentCulture propiedad.If you are changing the current culture of your application explicitly, you should also remember that the resource manager retrieves a resource set based on the value of the CultureInfo.CurrentUICulture property, and not the CultureInfo.CurrentCulture property. Normalmente, si cambia un valor, también debe cambiar el otro.Typically, if you change one value, you should also change the other.
Control de versiones de recursosResource Versioning
Dado que el ensamblado principal que contiene los recursos predeterminados de una aplicación es independiente de los ensamblados satélite de la aplicación, puede publicar una nueva versión del ensamblado principal sin tener que volver a implementar los ensamblados satélite.Because the main assembly that contains an app's default resources is separate from the app's satellite assemblies, you can release a new version of your main assembly without redeploying the satellite assemblies. Use el SatelliteContractVersionAttribute atributo para usar los ensamblados satélite existentes e indique al administrador de recursos que no vuelva a implementarlos con una nueva versión del ensamblado principal.You use the SatelliteContractVersionAttribute attribute to use existing satellite assemblies and instruct the resource manager not to redeploy them with a new version of your main assembly,
Para obtener más información sobre la compatibilidad de versiones de los ensamblados satélite, vea el artículo recuperar recursos.For more information about versioning support for satellite assemblies, see the article Retrieving Resources.
<satelliteassemblies> Nodo del archivo de configuración<satelliteassemblies> Configuration File Node
En el caso de los ejecutables que se implementan y ejecutan desde un sitio web (archivos HREF. exe), el ResourceManager objeto puede sondear los ensamblados satélite a través de la web, lo que puede afectar al rendimiento de la aplicación.For executables that are deployed and run from a website (HREF .exe files), the ResourceManager object may probe for satellite assemblies over the web, which can hurt your app's performance. Para eliminar el problema de rendimiento, puede limitar este sondeo a los ensamblados satélite que ha implementado con la aplicación.To eliminate the performance problem, you can limit this probing to the satellite assemblies that you have deployed with your app. Para ello, cree un <satelliteassemblies> nodo en el archivo de configuración de la aplicación para especificar que ha implementado un conjunto específico de referencias culturales para la aplicación y que el ResourceManager objeto no debe intentar sondear en busca de ninguna referencia cultural que no aparezca en ese nodo.To do this, you create a <satelliteassemblies> node in your app's configuration file to specify that you have deployed a specific set of cultures for your app, and that the ResourceManager object should not try to probe for any culture that is not listed in that node.
Nota
La alternativa preferida para crear un <satelliteassemblies> nodo es usar la característica manifiesto de implementación de ClickOnce .The preferred alternative to creating a <satelliteassemblies> node is to use the ClickOnce Deployment Manifest feature.
En el archivo de configuración de la aplicación, cree una sección similar a la siguiente:In your app's configuration file, create a section similar to the following:
<?xml version ="1.0"?>
<configuration>
<satelliteassemblies>
<assembly name="MainAssemblyName, Version=versionNumber, Culture=neutral, PublicKeyToken=null|yourPublicKeyToken">
<culture>cultureName1</culture>
<culture>cultureName2</culture>
<culture>cultureName3</culture>
</assembly>
</satelliteassemblies>
</configuration>
Edite esta información de configuración como se indica a continuación:Edit this configuration information as follows:
Especifique uno o más
<assembly>nodos para cada ensamblado principal que implemente, donde cada nodo especifica un nombre de ensamblado completo.Specify one or more<assembly>nodes for each main assembly that you deploy, where each node specifies a fully qualified assembly name. Especifique el nombre del ensamblado principal en lugar de MainAssemblyName y especifique losVersionvalores dePublicKeyTokenatributo, yCultureque se corresponden con el ensamblado principal.Specify the name of your main assembly in place of MainAssemblyName, and specify theVersion,PublicKeyToken, andCultureattribute values that correspond to your main assembly.En el
Versionatributo, especifique el número de versión del ensamblado.For theVersionattribute, specify the version number of your assembly. Por ejemplo, la primera versión del ensamblado podría ser el número de versión 1.0.0.0.For example, the first release of your assembly might be version number 1.0.0.0.Para el
PublicKeyTokenatributo, especifique la palabra clavenullsi no ha firmado el ensamblado con un nombre seguro o especifique el token de clave pública si ha firmado el ensamblado.For thePublicKeyTokenattribute, specify the keywordnullif you have not signed your assembly with a strong name, or specify your public key token if you have signed your assembly.Para el
Cultureatributo, especifique la palabra claveneutralpara designar el ensamblado principal y hacer que la ResourceManager clase sondee solo las referencias culturales que aparecen en los<culture>nodos.For theCultureattribute, specify the keywordneutralto designate the main assembly and cause the ResourceManager class to probe only for the cultures listed in the<culture>nodes.Para obtener más información sobre los nombres de ensamblado completos, vea el artículo nombres de ensamblados.For more information about fully qualified assembly names, see the article Assembly Names. Para obtener más información sobre los ensamblados con nombre seguro, vea el artículo creación y uso de ensamblados con nombre seguro.For more information about strong-named assemblies, see the article Create and use strong-named assemblies.
Especifique uno o más
<culture>nodos con un nombre de referencia cultural específico, como "fr-fr", o un nombre de referencia cultural neutro, como "fr".Specify one or more<culture>nodes with a specific culture name, such as "fr-FR", or a neutral culture name, such as "fr".
Si se necesitan recursos para cualquier ensamblado que no aparezca en el <satelliteassemblies> nodo, la ResourceManager clase sondea las referencias culturales mediante reglas de sondeo estándar.If resources are needed for any assembly not listed under the <satelliteassemblies> node, the ResourceManager class probes for cultures using standard probing rules.
Aplicaciones de la tienda Windows 8. xWindows 8.x Store Apps
Importante
Aunque la ResourceManager clase se admite en las aplicaciones de la tienda Windows 8. x, no se recomienda su uso.Although the ResourceManager class is supported in Windows 8.x Store apps, we do not recommend its use. Use esta clase solo cuando desarrolle proyectos de biblioteca de clases portable que se pueden usar con aplicaciones de la tienda Windows 8. x.Use this class only when you develop Portable Class Library projects that can be used with Windows 8.x Store apps. Para recuperar recursos de aplicaciones de la tienda Windows 8. x, use en su lugar la clase Windows. ApplicationModel. Resources. ResourceLoader .To retrieve resources from Windows 8.x Store apps, use the Windows.ApplicationModel.Resources.ResourceLoader class instead.
En el caso de las aplicaciones de la tienda Windows 8. x, la ResourceManager clase recupera los recursos de los archivos de índice de recursos del paquete (PRI).For Windows 8.x Store apps, the ResourceManager class retrieves resources from package resource index (PRI) files. Un único archivo PRI (el archivo PRI del paquete de aplicación) contiene los recursos de la referencia cultural predeterminada y las referencias culturales localizadas.A single PRI file (the application package PRI file) contains the resources for both the default culture and any localized cultures. La utilidad MakePRI se usa para crear un archivo PRI a partir de uno o más archivos de recursos que están en formato de recursos XML (. resw).You use the MakePRI utility to create a PRI file from one or more resource files that are in XML resource (.resw) format. En el caso de los recursos que se incluyen en un proyecto de Visual Studio, Visual Studio controla el proceso de creación y empaquetado automático del archivo PRI.For resources that are included in a Visual Studio project, Visual Studio handles the process of creating and packaging the PRI file automatically. Después, puede usar la ResourceManager clase .NET Framework para tener acceso a los recursos de la aplicación o de la biblioteca.You can then use the .NET Framework ResourceManager class to access the app's or library's resources.
Puede crear una instancia de un ResourceManager objeto para una aplicación de la tienda Windows 8. x de la misma manera que lo hace para una aplicación de escritorio.You can instantiate a ResourceManager object for a Windows 8.x Store app in the same way that you do for a desktop app.
Después, puede tener acceso a los recursos de una referencia cultural determinada pasando el nombre del recurso que se va a recuperar al GetString(String) método.You can then access the resources for a particular culture by passing the name of the resource to be retrieved to the GetString(String) method. De forma predeterminada, este método devuelve el recurso para la referencia cultural determinada por la referencia cultural de la interfaz de usuario actual del subproceso que realizó la llamada.By default, this method returns the resource for the culture determined by the current UI culture of the thread that made the call. También puede recuperar los recursos de una referencia cultural concreta pasando el nombre del recurso y un CultureInfo objeto que representa la referencia cultural cuyo recurso se va a recuperar en el GetString(String, CultureInfo) método.You can also retrieve the resources for a specific culture by passing the name of the resource and a CultureInfo object that represents the culture whose resource is to be retrieved to the GetString(String, CultureInfo) method. Si no se encuentra el recurso para la referencia cultural de la interfaz de usuario actual o la referencia cultural especificada, el administrador de recursos usa una lista de reserva del idioma de la interfaz de usuario para buscar un recurso adecuado.If the resource for the current UI culture or the specified culture cannot be found, the resource manager uses a UI language fallback list to locate a suitable resource.
Constructores
| ResourceManager() |
Inicializa una nueva instancia de la clase ResourceManager con valores predeterminados.Initializes a new instance of the ResourceManager class with default values. |
| ResourceManager(String, Assembly) |
Inicializa una nueva instancia de la clase ResourceManager que busca los recursos que contienen los archivos con el nombre raíz especificado, en el objeto dado.Initializes a new instance of the ResourceManager class that looks up resources contained in files with the specified root name in the given assembly. |
| ResourceManager(String, Assembly, Type) |
Inicializa una nueva instancia de la clase ResourceManager que usa un ResourceSet especificado para buscar recursos que contenga archivos con el nombre de raíz especificado en el ensamblado determinado.Initializes a new instance of the ResourceManager class that uses a specified ResourceSet class to look up resources contained in files with the specified root name in the given assembly. |
| ResourceManager(Type) |
Inicializa una nueva instancia de la clase ResourceManager que busca recursos en los ensamblados satélite a partir de la información del objeto de tipo especificado.Initializes a new instance of the ResourceManager class that looks up resources in satellite assemblies based on information from the specified type object. |
Campos
| BaseNameField |
Especifica el nombre raíz de los archivos de recursos donde ResourceManager busca recursos.Specifies the root name of the resource files that the ResourceManager searches for resources. |
| HeaderVersionNumber |
Especifica la versión de los encabezados de archivos de recursos que la implementación actual de ResourceManager puede interpretar y producir.Specifies the version of resource file headers that the current implementation of ResourceManager can interpret and produce. |
| MagicNumber |
Conserva el número usado para identificar los archivos de recursos.Holds the number used to identify resource files. |
| MainAssembly |
Especifica el ensamblado principal que contiene los recursos.Specifies the main assembly that contains the resources. |
| ResourceSets |
Obsoleto.
Contiene un objeto Hashtable que devuelve una asignación de referencias culturales a objetos ResourceSet.Contains a Hashtable that returns a mapping from cultures to ResourceSet objects. |
Propiedades
| BaseName |
Obtiene el nombre raíz de los archivos de recursos donde ResourceManager busca recursos.Gets the root name of the resource files that the ResourceManager searches for resources. |
| FallbackLocation |
Obtiene o establece la ubicación de la que se recuperan los recursos de reserva predeterminados.Gets or sets the location from which to retrieve default fallback resources. |
| IgnoreCase |
Obtiene o establece un valor que indica si el administrador de recursos permite realizar búsquedas de recursos sin distinción entre mayúsculas y minúsculas en los métodos GetString(String) y GetObject(String).Gets or sets a value that indicates whether the resource manager allows case-insensitive resource lookups in the GetString(String) and GetObject(String) methods. |
| ResourceSetType |
Obtiene el tipo de objeto de conjunto de recursos que el administrador de recursos usa para construir un objeto ResourceSet.Gets the type of the resource set object that the resource manager uses to construct a ResourceSet object. |
Métodos
| CreateFileBasedResourceManager(String, String, Type) |
Devuelve un objeto ResourceManager que busca un directorio específico en lugar de en el manifiesto del ensamblado para recursos.Returns a ResourceManager object that searches a specific directory instead of an assembly manifest for resources. |
| Equals(Object) |
Determina si el objeto especificado es igual que el objeto actual.Determines whether the specified object is equal to the current object. (Heredado de Object) |
| GetHashCode() |
Sirve como la función hash predeterminada.Serves as the default hash function. (Heredado de Object) |
| GetNeutralResourcesLanguage(Assembly) |
Devuelve información específica de la referencia cultural para los recursos predeterminados del ensamblado recuperando el valor del atributo NeutralResourcesLanguageAttribute en un ensamblado específico.Returns culture-specific information for the main assembly's default resources by retrieving the value of the NeutralResourcesLanguageAttribute attribute on a specified assembly. |
| GetObject(String) |
Devuelve el valor del recurso que no sea de cadena especificado.Returns the value of the specified non-string resource. |
| GetObject(String, CultureInfo) |
Obtiene el valor del recurso especificado de cadena no adaptado a la referencia cultural especificada.Gets the value of the specified non-string resource localized for the specified culture. |
| GetResourceFileName(CultureInfo) |
Genera el nombre del archivo de recursos para el objeto CultureInfo especificado.Generates the name of the resource file for the given CultureInfo object. |
| GetResourceSet(CultureInfo, Boolean, Boolean) |
Recupera el conjunto de recursos para una referencia cultural determinada.Retrieves the resource set for a particular culture. |
| GetSatelliteContractVersion(Assembly) |
Devuelve la versión especificada por el atributo SatelliteContractVersionAttribute en el ensamblado especificado.Returns the version specified by the SatelliteContractVersionAttribute attribute in the given assembly. |
| GetStream(String) |
Devuelve un objeto de secuencia de memoria no administrada del recurso especificado.Returns an unmanaged memory stream object from the specified resource. |
| GetStream(String, CultureInfo) |
Devuelve un objeto de secuencia de memoria no administrada a partir del recurso especificado, usando la referencia cultural especificada.Returns an unmanaged memory stream object from the specified resource, using the specified culture. |
| GetString(String) |
Devuelve el valor del recurso de cadena especificado.Returns the value of the specified string resource. |
| GetString(String, CultureInfo) |
Devuelve el valor del recurso de cadena adaptado a la referencia cultural especificada.Returns the value of the string resource localized for the specified culture. |
| GetType() |
Obtiene el Type de la instancia actual.Gets the Type of the current instance. (Heredado de Object) |
| InternalGetResourceSet(CultureInfo, Boolean, Boolean) |
Proporciona la implementación para buscar un conjunto de recursos.Provides the implementation for finding a resource set. |
| MemberwiseClone() |
Crea una copia superficial del Object actual.Creates a shallow copy of the current Object. (Heredado de Object) |
| ReleaseAllResources() |
Indica al administrador de recursos que llame al método Close() en todos los objetos ResourceSet y libere todos los recursos.Tells the resource manager to call the Close() method on all ResourceSet objects and release all resources. |
| ToString() |
Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object. (Heredado de Object) |
Se aplica a
Seguridad para subprocesos
Este tipo es seguro para la ejecución de subprocesos.This type is thread safe.