ResXResourceReader ResXResourceReader ResXResourceReader ResXResourceReader Class

定義

列舉 XML 資源 (.resx) 檔和資料流,並讀取資源的循序名稱值配對。Enumerates XML resource (.resx) files and streams, and reads the sequential resource name and value pairs.

public ref class ResXResourceReader : System::Resources::IResourceReader
public class ResXResourceReader : System.Resources.IResourceReader
type ResXResourceReader = class
    interface IResourceReader
    interface IEnumerable
    interface IDisposable
Public Class ResXResourceReader
Implements IResourceReader
繼承
ResXResourceReaderResXResourceReaderResXResourceReaderResXResourceReader
實作

範例

下列範例示範如何使用ResXResourceReader來逐一查看.resx 檔案中的資源。The following example demonstrates how to use a ResXResourceReader to iterate through the resources in a .resx file. 首先, ResXResourceReader rsxr檔案建立items.resxFirst, the ResXResourceReaderrsxr is created for the file items.resx. 下一步GetEnumerator方法用來建立IDictionaryEnumerator逐一查看資源,並對主控台顯示內容。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
Imports System.Resources
Imports System.Collections
Imports Microsoft.VisualBasic

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

備註

ResXResourceReader類別提供的預設實作IResourceReader讀取的 XML 格式的資源資訊的介面。The ResXResourceReader class provides a default implementation of the IResourceReader interface that reads resource information in an XML format. 若要從二進位資源的格式讀取資源資訊,請使用ResourceReader類別。To read resource information from a binary resource format, use the ResourceReader class.

您使用ResXResourceReader類別來周遊的字典列舉值來列舉.resx 檔案中的資源 (IDictionaryEnumerator) 時所傳回GetEnumerator方法。You use the ResXResourceReader class to enumerate resources in .resx files by traversing the dictionary enumerator (IDictionaryEnumerator) that is returned by the GetEnumerator method. 呼叫所提供的方法IDictionaryEnumerator前進到下一個資源,以及讀取的名稱和每個資源的.resx 檔案中的值。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.

注意

ResXResourceReader類別提供兩個列舉值。The ResXResourceReader class provides two enumerators. ResXResourceReader.GetEnumerator方法會傳回IDictionaryEnumerator物件; 我們建議您使用這個方法,來列舉資源。The ResXResourceReader.GetEnumerator method returns an IDictionaryEnumerator object; we recommend that you use this method to enumerate resources. ResXResourceReader.IEnumerable.GetEnumerator方法會傳回明確介面實作IEnumerator物件; 我們不建議使用它。The ResXResourceReader.IEnumerable.GetEnumerator method is an explicit interface implementation that returns an IEnumerator object; we do not recommend its use.

下列範例會使用GetEnumerator方法,以取得IDictionaryEnumerator物件,可用來列舉.resx 檔案中的資源。The following example uses the GetEnumerator method to obtain an IDictionaryEnumerator object that is used to enumerate the resources in a .resx file. 此範例也包含CreateResourceFile常式,它會建立必要的資源檔。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

如果UseResXDataNodes屬性是true,值IDictionaryEnumerator.Value屬性是ResXDataNode物件而不是資源的值。If the UseResXDataNodes property is true, the value of the IDictionaryEnumerator.Value property is a ResXDataNode object rather than the resource value. 這可讓資源項目的註解可從ResXDataNode.Comment屬性。This makes a resource item's comment available from the ResXDataNode.Comment property. 下列範例會設定UseResXDataNodes屬性設true並列舉.resx 檔案中的資源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

如果UseResXDataNodestrue,則ResXDataNode列舉中的項目可以是:If UseResXDataNodes is true, the ResXDataNode items in the enumeration can be either:

  • 連同其資料的具名的資源。Named resources along with their data. 在此情況下,ResXDataNode.FileRef屬性是nullIn this case, the ResXDataNode.FileRef property is null.

  • 名為資源,以及包含資源資料檔案的名稱。Named resources along with the name of the file that contains the resource data. 在此情況下,ResXDataNode.FileRef屬性會傳回ResXFileRef提供資源,包括其檔案名稱的相關資訊的物件。In this case, the ResXDataNode.FileRef property returns a ResXFileRef object that provides information about the resource, including its filename. 如果使用相對檔案名稱,您都應該設定BasePath屬性提供的參考點的相對檔案路徑。If relative file names are used, you should always set the BasePath property to provide a reference point for the relative file path.

如果您想從.resx 檔擷取具名的資源,而不是列舉其資源,您可以具現化ResXResourceSet物件並呼叫其GetStringGetObject方法。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.

注意

ResXResourceReader類別包含的連結要求和繼承要求套用到所有成員的類別層級。The ResXResourceReader class contains a link demand and an inheritance demand at the class level that applies to all members. ASecurityException立即呼叫端或衍生的類別不具有完全信任權限時,會擲回例外狀況。A SecurityException exception is thrown when either the immediate caller or the derived class does not have full-trust permission.

建構函式

ResXResourceReader(Stream) ResXResourceReader(Stream) ResXResourceReader(Stream) ResXResourceReader(Stream)

為指定的資料流,初始化 ResXResourceReader 類別的新執行個體。Initializes a new instance of the ResXResourceReader class for the specified stream.

ResXResourceReader(Stream, AssemblyName[]) ResXResourceReader(Stream, AssemblyName[]) ResXResourceReader(Stream, AssemblyName[]) ResXResourceReader(Stream, AssemblyName[])

使用資料流和組件 (Assembly) 名稱陣列,初始化 ResXResourceReader 類別的新執行個體。Initializes a new instance of the ResXResourceReader class using a stream and an array of assembly names.

ResXResourceReader(Stream, ITypeResolutionService) ResXResourceReader(Stream, ITypeResolutionService) ResXResourceReader(Stream, ITypeResolutionService) ResXResourceReader(Stream, ITypeResolutionService)

使用輸入資料流和型別解析服務,初始化 ResXResourceReader 類別的新執行個體。Initializes a new instance of the ResXResourceReader class using an input stream and a type resolution service.

ResXResourceReader(String) ResXResourceReader(String) ResXResourceReader(String) ResXResourceReader(String)

為指定的資源檔,初始化 ResXResourceReader 類別的新執行個體。Initializes a new instance of the ResXResourceReader class for the specified resource file.

ResXResourceReader(String, AssemblyName[]) ResXResourceReader(String, AssemblyName[]) ResXResourceReader(String, AssemblyName[]) ResXResourceReader(String, AssemblyName[])

使用 XML 資源檔名稱和組件名稱陣列,初始化 ResXResourceReader 類別的新執行個體。Initializes a new instance of the ResXResourceReader class using an XML resource file name and an array of assembly names.

ResXResourceReader(String, ITypeResolutionService) ResXResourceReader(String, ITypeResolutionService) ResXResourceReader(String, ITypeResolutionService) ResXResourceReader(String, ITypeResolutionService)

使用檔名和型別解析服務,初始化 ResXResourceReader 類別的新執行個體。Initializes a new instance of the ResXResourceReader class using a file name and a type resolution service.

ResXResourceReader(TextReader) ResXResourceReader(TextReader) ResXResourceReader(TextReader) ResXResourceReader(TextReader)

為指定的 TextReader 初始化 ResXResourceReader 類別的新執行個體。Initializes a new instance of the ResXResourceReader class for the specified TextReader.

ResXResourceReader(TextReader, AssemblyName[]) ResXResourceReader(TextReader, AssemblyName[]) ResXResourceReader(TextReader, AssemblyName[]) ResXResourceReader(TextReader, AssemblyName[])

使用 ResXResourceReader 物件和組件名稱陣列,初始化 TextReader 類別的新執行個體。Initializes a new instance of the ResXResourceReader class using a TextReader object and an array of assembly names.

ResXResourceReader(TextReader, ITypeResolutionService) ResXResourceReader(TextReader, ITypeResolutionService) ResXResourceReader(TextReader, ITypeResolutionService) ResXResourceReader(TextReader, ITypeResolutionService)

使用文字資料流讀取器和型別解析服務,初始化 ResXResourceReader 類別的新執行個體。Initializes a new instance of the ResXResourceReader class using a text stream reader and a type resolution service.

屬性

BasePath BasePath BasePath BasePath

取得或設定 ResXFileRef 物件中指定之相對檔案路徑的基底路徑。Gets or sets the base path for the relative file path specified in a ResXFileRef object.

UseResXDataNodes UseResXDataNodes UseResXDataNodes UseResXDataNodes

取得或設定值,指出讀取目前的 XML 資源檔或資料流時,是否會傳回 ResXDataNode 物件。Gets or sets a value that indicates whether ResXDataNode objects are returned when reading the current XML resource file or stream.

方法

Close() Close() Close() Close()

釋放 ResXResourceReader 所使用的所有資源。Releases all resources used by the ResXResourceReader.

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

釋放 ResXResourceReader 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the ResXResourceReader and optionally releases the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

這個成員會覆寫 Finalize() 方法。This member overrides the Finalize() method.

FromFileContents(String) FromFileContents(String) FromFileContents(String) FromFileContents(String)

建立新的 ResXResourceReader 物件,並將其初始化,以讀取內容為 XML 資源檔格式的字串。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[]) FromFileContents(String, AssemblyName[]) FromFileContents(String, AssemblyName[]) FromFileContents(String, AssemblyName[])

建立新的 ResXResourceReader 物件,並將其初始化,以讀取內容為 XML 資源檔格式的字串,並使用 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) FromFileContents(String, ITypeResolutionService) FromFileContents(String, ITypeResolutionService) FromFileContents(String, ITypeResolutionService)

建立新的 ResXResourceReader 物件,並將其初始化,以讀取內容為 XML 資源檔格式的字串,並使用 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() GetEnumerator() GetEnumerator() GetEnumerator()

傳回目前 ResXResourceReader 物件的列舉值。Returns an enumerator for the current ResXResourceReader object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetMetadataEnumerator() GetMetadataEnumerator() GetMetadataEnumerator() GetMetadataEnumerator()

提供字典列舉值,其可從目前的 XML 資源檔或資料流中擷取設計階段屬性。Provides a dictionary enumerator that can retrieve the design-time properties from the current XML resource file or stream.

GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

明確介面實作

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

釋放 ResXResourceReader 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the ResXResourceReader and optionally releases the managed resources. 如需這個成員的描述,請參閱 Dispose() 方法。For a description of this member, see the Dispose() method.

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

傳回目前 ResXResourceReader 物件的列舉值。Returns an enumerator for the current ResXResourceReader object. 如需這個成員的描述,請參閱 GetEnumerator() 方法。For a description of this member, see the GetEnumerator() method.

Extension Methods

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

啟用查詢的平行化作業。Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

將轉換IEnumerableIQueryableConverts an IEnumerable to an IQueryable.

安全性

LinkDemand
針對完全信任立即呼叫端。for full trust for the immediate caller. 這個成員無法供部分信任的程式碼使用。This member cannot be used by partially trusted code.

InheritanceDemand
針對繼承者完全信任。for full trust for inheritors. 這個類別無法繼承由部分信任的程式碼。This class cannot be inherited by partially trusted code.

適用於

另請參閱