ResXResourceReader 類別

定義

列舉 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
繼承
ResXResourceReader
實作

範例

下列範例示範如何使用ResXResourceReader來逐一查看 .resx 檔案中的資源。The following example demonstrates how to use a ResXResourceReader to iterate through the resources in a .resx file. 首先, ResXResourceReader rsxritems.resx為檔案建立。First, 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.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

備註

類別會提供IResourceReader介面的預設執行, 以 XML 格式讀取資源資訊。 ResXResourceReaderThe 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 GetEnumerator方法所傳回的字典列舉值 (IDictionaryEnumerator), 您可以使用類別來列舉 .resx 檔案中的資源。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. 方法是會傳回IEnumerator物件的明確介面實作為, 我們不建議使用它。 ResXResourceReader.IEnumerable.GetEnumeratorThe 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

如果屬性為true ResXDataNode , 則屬性的值會是物件, 而不是資源值。 IDictionaryEnumerator.Value UseResXDataNodesIf 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

如果UseResXDataNodes ResXDataNodetrue, 則列舉中的專案可以是: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具現化物件GetString , GetObject並呼叫其和方法。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. 當立即呼叫端或衍生類別沒有完全信任許可權時, 就會擲回例外狀況(exception)。SecurityExceptionA SecurityException exception is thrown when either the immediate caller or the derived class does not have full-trust permission.

建構函式

ResXResourceReader(Stream)

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

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 類別的新執行個體。Initializes a new instance of the ResXResourceReader class using an input stream and a type resolution service.

ResXResourceReader(String)

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

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 類別的新執行個體。Initializes a new instance of the ResXResourceReader class using a file name and a type resolution service.

ResXResourceReader(TextReader)

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

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 類別的新執行個體。Initializes a new instance of the ResXResourceReader class using a text stream reader and a type resolution service.

屬性

BasePath

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

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()

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

Dispose(Boolean)

釋放 ResXResourceReader 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。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.

(繼承來源 Object)
Finalize()

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

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[])

建立新的 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)

建立新的 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()

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

GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetMetadataEnumerator()

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

GetType()

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

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

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

(繼承來源 Object)

明確介面實作

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()

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

擴充方法

Cast<TResult>(IEnumerable)

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

OfType<TResult>(IEnumerable)

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

AsParallel(IEnumerable)

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

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryableConverts 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.

適用於

另請參閱