Bewerken

Share via


ResXResourceReader Class

Definition

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

public ref class ResXResourceReader : System::Resources::IResourceReader
public ref class ResXResourceReader : IDisposable, System::Collections::IEnumerable, System::Resources::IResourceReader
public class ResXResourceReader : System.Resources.IResourceReader
public class ResXResourceReader : IDisposable, System.Collections.IEnumerable, System.Resources.IResourceReader
type ResXResourceReader = class
    interface IResourceReader
    interface IEnumerable
    interface IDisposable
Public Class ResXResourceReader
Implements IResourceReader
Public Class ResXResourceReader
Implements IDisposable, IEnumerable, IResourceReader
Inheritance
ResXResourceReader
Implements

Examples

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.windows.forms.dll>
#using <System.dll>

using namespace System;
using namespace System::Resources;
using namespace System::Collections;
void main()
{

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


   // Iterate through the resources and display the contents to the console.
   IEnumerator^ myEnum = rsxr->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      DictionaryEntry^ d = safe_cast<DictionaryEntry^>(myEnum->Current);
      Console::WriteLine( "{0}:\t {1}", d->Key, d->Value );
   }


   //Close the reader.
   rsxr->Close();
}
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();
   }
}
Imports System.Resources
Imports System.Collections

Class ReadResXResources
   
   Public Shared Sub Main()
      
      ' Create a ResXResourceReader for the file items.resx.
      Dim rsxr As ResXResourceReader
      rsxr = New ResXResourceReader("items.resx")

      ' Iterate through the resources and display the contents to the console.
      Dim d As DictionaryEntry
      For Each d In  rsxr
         Console.WriteLine(d.Key.ToString() + ":" + ControlChars.Tab + d.Value.ToString())
      Next d
      
      'Close the reader.
      rsxr.Close()

   End Sub

End Class

Remarks

Important

Calling methods from this class with untrusted data is a security risk. Call the methods from this class only with trusted data. For more information, see Validate All Inputs.

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.

Note

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
Imports System.Collections
Imports System.Resources

Module Example
   Private Const resxFilename As String = ".\CountryHeaders.resx"
     
   Public Sub Main()
      ' Create a resource file to read.
      CreateResourceFile()
      
      ' Enumerate the resources in the file.
      Dim rr As New ResXResourceReader(resxFilename)
      Dim dict As IDictionaryEnumerator = rr.GetEnumerator()
      Do While dict.MoveNext()
         Console.WriteLine("{0}: {1}", dict.Key, dict.Value)   
      Loop
   End Sub
   
   Private Sub CreateResourceFile()
      Dim rw As New ResxResourceWriter(resxFilename)
      Dim resNames() As String = {"Country", "Population", "Area", 
                                  "Capital", "LCity" }
      Dim columnHeaders() As String = { "Country Name", "Population (2010}", 
                                        "Area", "Capital", "Largest City" }
      Dim comments() As String = { "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 ctr As Integer = 0 To resNames.Length - 1
         Dim node As New ResXDataNode(resNames(ctr), columnHeaders(ctr))
         node.Comment = comments(ctr)
         rw.AddResource(node)
      Next
      rw.Generate()
      rw.Close()
   End Sub
End Module
' 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
Imports System.Collections
Imports System.ComponentModel.Design
Imports System.Resources

Module Example
   Private Const resxFilename As String = ".\CountryHeaders.resx"
     
   Public Sub Main()
      ' Create a resource file to read.
      CreateResourceFile()
      
      ' Enumerate the resources in the file.
      Dim rr As New ResXResourceReader(resxFilename)
      rr.UseResXDataNodes = True
      Dim dict As IDictionaryEnumerator = rr.GetEnumerator()
      Do While dict.MoveNext()
         Dim node As ResXDataNode = DirectCast(dict.Value, ResXDataNode)
         Console.WriteLine("{0,-20} {1,-20} {2}", 
                           node.Name + ":", 
                           node.GetValue(CType(Nothing, ITypeResolutionService)), 
                           If(Not String.IsNullOrEmpty(node.Comment), "// " + node.Comment, ""))
      Loop
   End Sub
   
   Private Sub CreateResourceFile()
      Dim rw As New ResxResourceWriter(resxFilename)
      Dim resNames() As String = {"Country", "Population", "Area", 
                                  "Capital", "LCity" }
      Dim columnHeaders() As String = { "Country Name", "Population (2010}", 
                                        "Area", "Capital", "Largest City" }
      Dim comments() As String = { "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 ctr As Integer = 0 To resNames.Length - 1
         Dim node As New ResXDataNode(resNames(ctr), columnHeaders(ctr))
         node.Comment = comments(ctr)
         rw.AddResource(node)
      Next
      rw.Generate()
      rw.Close()
   End Sub
End Module
' 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.

Note

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.

Constructors

ResXResourceReader(Stream)

Initializes a new instance of the ResXResourceReader class for the specified stream.

ResXResourceReader(Stream, AssemblyName[])

Initializes a new instance of the ResXResourceReader class using a stream and an array of assembly names.

ResXResourceReader(Stream, ITypeResolutionService)

Initializes a new instance of the ResXResourceReader class using an input stream and a type resolution service.

ResXResourceReader(String)

Initializes a new instance of the ResXResourceReader class for the specified resource file.

ResXResourceReader(String, AssemblyName[])

Initializes a new instance of the ResXResourceReader class using an XML resource file name and an array of assembly names.

ResXResourceReader(String, ITypeResolutionService)

Initializes a new instance of the ResXResourceReader class using a file name and a type resolution service.

ResXResourceReader(TextReader)

Initializes a new instance of the ResXResourceReader class for the specified TextReader.

ResXResourceReader(TextReader, AssemblyName[])

Initializes a new instance of the ResXResourceReader class using a TextReader object and an array of assembly names.

ResXResourceReader(TextReader, ITypeResolutionService)

Initializes a new instance of the ResXResourceReader class using a text stream reader and a type resolution service.

Properties

BasePath

Gets or sets the base path for the relative file path specified in a ResXFileRef object.

UseResXDataNodes

Gets or sets a value that indicates whether ResXDataNode objects are returned when reading the current XML resource file or stream.

Methods

Close()

Releases all resources used by the ResXResourceReader.

Dispose(Boolean)

Releases the unmanaged resources used by the ResXResourceReader and optionally releases the managed resources.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize()

This member overrides the Finalize() method.

FromFileContents(String)

Creates a new ResXResourceReader object and initializes it to read a string whose contents are in the form of an XML resource file.

FromFileContents(String, AssemblyName[])

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.

FromFileContents(String, ITypeResolutionService)

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.

GetEnumerator()

Returns an enumerator for the current ResXResourceReader object.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetMetadataEnumerator()

Provides a dictionary enumerator that can retrieve the design-time properties from the current XML resource file or stream.

GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

IDisposable.Dispose()

Releases the unmanaged resources used by the ResXResourceReader and optionally releases the managed resources. For a description of this member, see the Dispose() method.

IEnumerable.GetEnumerator()

Returns an enumerator for the current ResXResourceReader object. For a description of this member, see the GetEnumerator() method.

Extension Methods

Cast<TResult>(IEnumerable)

Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Enables parallelization of a query.

AsQueryable(IEnumerable)

Converts an IEnumerable to an IQueryable.

Applies to

See also