다음을 통해 공유


ResXResourceReader 클래스

정의

XML 리소스(.resx) 파일 및 스트림을 열거하고 순차 리소스 이름 및 값 쌍을 읽습니다.

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
상속
ResXResourceReader
구현

예제

다음 예제에서는 ResXResourceReader 사용하여 .resx 파일의 리소스를 반복하는 방법을 보여 줍니다. 먼저 파일 items.resx대한 ResXResourceReaderrsxr 만들어집니다. 다음으로, GetEnumerator 메서드는 리소스를 반복하고 콘텐츠를 콘솔에 표시하는 IDictionaryEnumerator 만드는 데 사용됩니다.

#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

설명

중요하다

신뢰할 수 없는 데이터를 사용하여 이 클래스에서 메서드를 호출하는 것은 보안 위험입니다. 신뢰할 수 있는 데이터로만 이 클래스의 메서드를 호출합니다. 자세한 내용은 모든 입력유효성 검사 참조하세요.

ResXResourceReader 클래스는 XML 형식으로 리소스 정보를 읽는 IResourceReader 인터페이스의 기본 구현을 제공합니다. 이진 리소스 형식에서 리소스 정보를 읽으려면 ResourceReader 클래스를 사용합니다.

ResXResourceReader 클래스를 사용하여 GetEnumerator 메서드에서 반환되는 사전 열거자(IDictionaryEnumerator)를 트래버스하여 .resx 파일의 리소스를 열거합니다. IDictionaryEnumerator 제공된 메서드를 호출하여 다음 리소스로 이동하고 .resx 파일에서 각 리소스의 이름과 값을 읽습니다.

메모

ResXResourceReader 클래스는 두 개의 열거자를 제공합니다. ResXResourceReader.GetEnumerator 메서드는 IDictionaryEnumerator 개체를 반환합니다. 이 메서드를 사용하여 리소스를 열거하는 것이 좋습니다. ResXResourceReader.IEnumerable.GetEnumerator 메서드는 IEnumerator 개체를 반환하는 명시적 인터페이스 구현입니다. 사용하지 않는 것이 좋습니다.

다음 예제에서는 GetEnumerator 메서드를 사용하여 .resx 파일에서 리소스를 열거하는 데 사용되는 IDictionaryEnumerator 개체를 가져옵니다. 이 예제에는 필요한 리소스 파일을 만드는 CreateResourceFile 루틴이 포함되어 있습니다.

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 개체입니다. 이렇게 하면 ResXDataNode.Comment 속성에서 리소스 항목의 주석을 사용할 수 있습니다. 다음 예제에서는 UseResXDataNodes 속성을 true 설정하고 .resx 파일의 리소스를 열거합니다.

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 true경우 열거형의 ResXDataNode 항목 중 하나일 수 있습니다.

  • 데이터와 함께 명명된 리소스입니다. 이 경우 ResXDataNode.FileRef 속성은 null.

  • 리소스 데이터가 포함된 파일의 이름과 함께 명명된 리소스입니다. 이 경우 ResXDataNode.FileRef 속성은 해당 파일 이름을 포함하여 리소스에 대한 정보를 제공하는 ResXFileRef 개체를 반환합니다. 상대 파일 이름을 사용하는 경우 항상 BasePath 속성을 설정하여 상대 파일 경로에 대한 참조 지점을 제공해야 합니다.

해당 리소스를 열거하지 않고 .resx 파일에서 명명된 리소스를 검색하려는 경우 ResXResourceSet 개체를 인스턴스화하고 해당 GetStringGetObject 메서드를 호출할 수 있습니다.

메모

ResXResourceReader 클래스에는 모든 멤버에 적용되는 클래스 수준의 링크 요청 및 상속 요청이 포함됩니다. 직접 호출자 또는 파생 클래스에 완전 신뢰 권한이 없는 경우 SecurityException 예외가 throw됩니다.

생성자

ResXResourceReader(Stream)

지정된 스트림에 대한 ResXResourceReader 클래스의 새 인스턴스를 초기화합니다.

ResXResourceReader(Stream, AssemblyName[])

스트림 및 어셈블리 이름 배열을 사용하여 ResXResourceReader 클래스의 새 인스턴스를 초기화합니다.

ResXResourceReader(Stream, ITypeResolutionService)

입력 스트림 및 형식 확인 서비스를 사용하여 ResXResourceReader 클래스의 새 인스턴스를 초기화합니다.

ResXResourceReader(String)

지정된 리소스 파일에 대한 ResXResourceReader 클래스의 새 인스턴스를 초기화합니다.

ResXResourceReader(String, AssemblyName[])

XML 리소스 파일 이름 및 어셈블리 이름 배열을 사용하여 ResXResourceReader 클래스의 새 인스턴스를 초기화합니다.

ResXResourceReader(String, ITypeResolutionService)

파일 이름 및 형식 확인 서비스를 사용하여 ResXResourceReader 클래스의 새 인스턴스를 초기화합니다.

ResXResourceReader(TextReader)

지정된 TextReader대한 ResXResourceReader 클래스의 새 인스턴스를 초기화합니다.

ResXResourceReader(TextReader, AssemblyName[])

TextReader 개체 및 어셈블리 이름 배열을 사용하여 ResXResourceReader 클래스의 새 인스턴스를 초기화합니다.

ResXResourceReader(TextReader, ITypeResolutionService)

텍스트 스트림 판독기 및 형식 확인 서비스를 사용하여 ResXResourceReader 클래스의 새 인스턴스를 초기화합니다.

속성

BasePath

ResXFileRef 개체에 지정된 상대 파일 경로의 기본 경로를 가져오거나 설정합니다.

UseResXDataNodes

현재 XML 리소스 파일 또는 스트림을 읽을 때 ResXDataNode 개체가 반환되는지 여부를 나타내는 값을 가져오거나 설정합니다.

메서드

Close()

ResXResourceReader사용하는 모든 리소스를 해제합니다.

Dispose(Boolean)

ResXResourceReader 사용하는 관리되지 않는 리소스를 해제하고 필요에 따라 관리되는 리소스를 해제합니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 여부를 확인합니다.

(다음에서 상속됨 Object)
Finalize()

이 멤버는 Finalize() 메서드를 재정의합니다.

FromFileContents(String)

ResXResourceReader 개체를 만들고 해당 내용이 XML 리소스 파일 형식인 문자열을 읽도록 초기화합니다.

FromFileContents(String, AssemblyName[])

ResXResourceReader 개체를 만들고 초기화하여 내용이 XML 리소스 파일 형식인 문자열을 읽고 AssemblyName 개체 배열을 사용하여 리소스에 지정된 형식 이름을 확인합니다.

FromFileContents(String, ITypeResolutionService)

ResXResourceReader 개체를 만들고 초기화하여 내용이 XML 리소스 파일 형식인 문자열을 읽고 ITypeResolutionService 개체를 사용하여 리소스에 지정된 형식 이름을 확인합니다.

GetEnumerator()

현재 ResXResourceReader 개체의 열거자를 반환합니다.

GetHashCode()

기본 해시 함수로 사용됩니다.

(다음에서 상속됨 Object)
GetMetadataEnumerator()

현재 XML 리소스 파일 또는 스트림에서 디자인 타임 속성을 검색할 수 있는 사전 열거자를 제공합니다.

GetType()

현재 인스턴스의 Type 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

명시적 인터페이스 구현

IDisposable.Dispose()

ResXResourceReader 사용하는 관리되지 않는 리소스를 해제하고 필요에 따라 관리되는 리소스를 해제합니다. 이 멤버에 대한 설명은 Dispose() 메서드를 참조하세요.

IEnumerable.GetEnumerator()

현재 ResXResourceReader 개체의 열거자를 반환합니다. 이 멤버에 대한 설명은 GetEnumerator() 메서드를 참조하세요.

확장 메서드

Cast<TResult>(IEnumerable)

IEnumerable 요소를 지정된 형식으로 캐스팅합니다.

OfType<TResult>(IEnumerable)

지정된 형식에 따라 IEnumerable 요소를 필터링합니다.

AsParallel(IEnumerable)

쿼리의 병렬 처리를 사용하도록 설정합니다.

AsQueryable(IEnumerable)

IEnumerable IQueryable변환합니다.

적용 대상

추가 정보