Export (0) Print
Expand All

ResXResourceReader Class

Enumerates XML resource (.resx) files and streams, and reads the sequential resource name and value pairs.

System.Object
  System.Resources.ResXResourceReader

Namespace:  System.Resources
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
public class ResXResourceReader : IResourceReader, 
	IEnumerable, IDisposable

The ResXResourceReader type exposes the following members.

  NameDescription
Public methodResXResourceReader(Stream)Initializes a new instance of the ResXResourceReader class for the specified stream.
Public methodResXResourceReader(String)Initializes a new instance of the ResXResourceReader class for the specified resource file.
Public methodResXResourceReader(TextReader)Initializes a new instance of the ResXResourceReader class for the specified TextReader.
Public methodResXResourceReader(Stream, ITypeResolutionService)Initializes a new instance of the ResXResourceReader class using an input stream and a type resolution service.
Public methodResXResourceReader(Stream, AssemblyName[])Initializes a new instance of the ResXResourceReader class using a stream and an array of assembly names.
Public methodResXResourceReader(String, ITypeResolutionService)Initializes a new instance of the ResXResourceReader class using a file name and a type resolution service.
Public methodResXResourceReader(String, AssemblyName[])Initializes a new instance of the ResXResourceReader class using an XML resource file name and an array of assembly names.
Public methodResXResourceReader(TextReader, ITypeResolutionService)Initializes a new instance of the ResXResourceReader class using a text stream reader and a type resolution service.
Public methodResXResourceReader(TextReader, AssemblyName[])Initializes a new instance of the ResXResourceReader class using a TextReader object and an array of assembly names.
Top

  NameDescription
Public propertyBasePathGets or sets the base path for the relative file path specified in a ResXFileRef object.
Public propertyUseResXDataNodesGets or sets a value that indicates whether ResXDataNode objects are returned when reading the current XML resource file or stream.
Top

  NameDescription
Public methodCloseReleases all resources used by the ResXResourceReader.
Protected methodDisposeReleases the unmanaged resources used by the ResXResourceReader and optionally releases the managed resources.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeThis member overrides the Finalize method. (Overrides Object.Finalize().)
Public methodStatic memberFromFileContents(String)Creates a new ResXResourceReader object and initializes it to read a string whose contents are in the form of an XML resource file.
Public methodStatic memberFromFileContents(String, ITypeResolutionService)Infrastructure. Creates a new ResXResourceReader object and initializes it to read a string whose contents are in the form of an XML resource file, and to use an ITypeResolutionService object to resolve type names specified in a resource.
Public methodStatic memberFromFileContents(String, AssemblyName[])Infrastructure. Creates a new ResXResourceReader object and initializes it to read a string whose contents are in the form of an XML resource file, and to use an array of AssemblyName objects to resolve type names specified in a resource.
Public methodGetEnumeratorReturns an enumerator for the current ResXResourceReader object.
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetMetadataEnumeratorProvides a dictionary enumerator that can retrieve the design-time properties from the current XML resource file or stream.
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Public Extension MethodAsParallelEnables parallelization of a query. (Defined by ParallelEnumerable.)
Public Extension MethodAsQueryableConverts an IEnumerable to an IQueryable. (Defined by Queryable.)
Public Extension MethodCast<TResult>Casts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
Public Extension MethodOfType<TResult>Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)
Top

  NameDescription
Explicit interface implemetationPrivate methodIDisposable.DisposeInfrastructure. Releases the unmanaged resources used by the ResXResourceReader and optionally releases the managed resources. For a description of this member, see the IDisposable.Dispose method.
Explicit interface implemetationPrivate methodIEnumerable.GetEnumeratorInfrastructure. Returns an enumerator for the current ResXResourceReader object. For a description of this member, see the IEnumerable.GetEnumerator method.
Top

The ResXResourceReader class provides a default implementation of the IResourceReader interface that reads resource information in an XML format. To read resource information from a binary resource format, use the ResourceReader class.

You use the ResXResourceReader class to enumerate resources in .resx files by traversing the dictionary enumerator (IDictionaryEnumerator) that is returned by the GetEnumerator method. You call the methods provided by IDictionaryEnumerator to advance to the next resource and to read the name and value of each resource in the .resx file.

NoteNote

The ResXResourceReader class provides two enumerators. The ResXResourceReader.GetEnumerator method returns an IDictionaryEnumerator object; we recommend that you use this method to enumerate resources. The ResXResourceReader.IEnumerable.GetEnumerator method is an explicit interface implementation that returns an IEnumerator object; we do not recommend its use.

The following example uses the GetEnumerator method to obtain an IDictionaryEnumerator object that is used to enumerate the resources in a .resx file. The example includes a CreateResourceFile routine that creates the necessary resource file.

using System;
using System.Collections;
using System.Resources;

public class Example
{
   private const string resxFilename = @".\CountryHeaders.resx";

   public static void Main()
   {
      // Create a resource file to read.
      CreateResourceFile();

      // Enumerate the resources in the file.
      ResXResourceReader rr = new ResXResourceReader(resxFilename);
      IDictionaryEnumerator dict = rr.GetEnumerator();
      while (dict.MoveNext())
         Console.WriteLine("{0}: {1}", dict.Key, dict.Value);   
   }

   private static void CreateResourceFile()
   {
      ResXResourceWriter rw = new ResXResourceWriter(resxFilename);
      string[] resNames = {"Country", "Population", "Area", 
                           "Capital", "LCity" };
      string[] columnHeaders = { "Country Name", "Population (2010}", 
                                 "Area", "Capital", "Largest City" };
      string[] comments = { "The localized country name", "", 
                            "The area in square miles", "", 
                            "The largest city based on 2010 data" };
      rw.AddResource("Title", "Country Information");
      rw.AddResource("nColumns", resNames.Length);
      for (int ctr = 0; ctr < resNames.Length; ctr++) {
         ResXDataNode node = new ResXDataNode(resNames[ctr], columnHeaders[ctr]);
         node.Comment = comments[ctr];
         rw.AddResource(node);
      }
      rw.Generate();
      rw.Close();
   }
}
// The example displays the following output: 
//       Title: Country Information 
//       nColumns: 5 
//       Country: Country Name 
//       Population: Population (2010} 
//       Area: Area 
//       Capital: Capital 
//       LCity: Largest City

If the UseResXDataNodes property is true, the value of the IDictionaryEnumerator.Value property is a ResXDataNode object rather than the resource value. This makes a resource item's comment available from the ResXDataNode.Comment property. The following example sets the UseResXDataNodes property to true and enumerates the resources in a .resx file,

using System;
using System.Collections;
using System.ComponentModel.Design;
using System.Resources;

public class Example
{
   private const string resxFilename = @".\CountryHeaders.resx";

   public static void Main()
   {
      // Create a resource file to read.
      CreateResourceFile();

      // Enumerate the resources in the file.
      ResXResourceReader rr = new ResXResourceReader(resxFilename);
      rr.UseResXDataNodes = true;
      IDictionaryEnumerator dict = rr.GetEnumerator();
      while (dict.MoveNext()) {
         ResXDataNode node = (ResXDataNode) dict.Value;
         Console.WriteLine("{0,-20} {1,-20} {2}", 
                           node.Name + ":", 
                           node.GetValue((ITypeResolutionService) null), 
                           ! String.IsNullOrEmpty(node.Comment) ? "// " + node.Comment : "");
      }
   }

   private static void CreateResourceFile()
   {
      ResXResourceWriter rw = new ResXResourceWriter(resxFilename);
      string[] resNames = {"Country", "Population", "Area", 
                           "Capital", "LCity" };
      string[] columnHeaders = { "Country Name", "Population (2010}", 
                                 "Area", "Capital", "Largest City" };
      string[] comments = { "The localized country name", "", 
                            "The area in square miles", "", 
                            "The largest city based on 2010 data" };
      rw.AddResource("Title", "Country Information");
      rw.AddResource("nColumns", resNames.Length);
      for (int ctr = 0; ctr < resNames.Length; ctr++) {
         ResXDataNode node = new ResXDataNode(resNames[ctr], columnHeaders[ctr]);
         node.Comment = comments[ctr];
         rw.AddResource(node);
      }
      rw.Generate();
      rw.Close();
   }
}
// The example displays the following output: 
//    Title:               Country Information 
//    nColumns:            5 
//    Country:             Country Name         // The localized country name 
//    Population:          Population (2010} 
//    Area:                Area                 // The area in square miles 
//    Capital:             Capital 
//    LCity:               Largest City         // The largest city based on 2010 data

If UseResXDataNodes is true, the ResXDataNode items in the enumeration can be either:

  • Named resources along with their data. In this case, the ResXDataNode.FileRef property is null.

  • Named resources along with the name of the file that contains the resource data. In this case, the ResXDataNode.FileRef property returns a ResXFileRef object that provides information about the resource, including its filename. If relative file names are used, you should always set the BasePath property to provide a reference point for the relative file path.

If you want to retrieve named resources from a .resx file rather than enumerating its resources, you can instantiate a ResXResourceSet object and call its GetString and GetObject methods.

NoteNote

The ResXResourceReader class contains a link demand and an inheritance demand at the class level that applies to all members. A SecurityException exception is thrown when either the immediate caller or the derived class does not have full-trust permission. For more information about security demands, see Link Demands and Inheritance Demands.

The following example demonstrates how to use a ResXResourceReader to iterate through the resources in a .resx file. First, the ResXResourceReader rsxr is created for the file items.resx. Next, the GetEnumerator method is used to create an IDictionaryEnumerator to iterate through the resources and display the contents to the console.

using System;
using System.Resources;
using System.Collections;

class ReadResXResources
{
   public static void Main()
   {

      // Create a ResXResourceReader for the file items.resx.
      ResXResourceReader rsxr = new ResXResourceReader("items.resx");

      // Iterate through the resources and display the contents to the console. 
      foreach (DictionaryEntry d in rsxr)
      {
    Console.WriteLine(d.Key.ToString() + ":\t" + d.Value.ToString());
      }

     //Close the reader.
     rsxr.Close();
   }
}

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft