Share via


InvariantCulture 속성 사용

[이 설명서는 미리 보기 전용이며, 이후 릴리스에서 변경될 수 있습니다. 비어 있는 항목은 자리 표시자로 포함됩니다.]

InvariantCulture 속성은 중립 문화권도 특정 문화권도 아니며 문화권을 구분하지 않는 제 3의 문화권 형식입니다. 이 속성은 영어와 연관되어 있으나 국가나 지역과는 관계가 없습니다. 응용 프로그램에서는 System.Globalization 네임스페이스에서 문화권이 필요한 거의 모든 메서드에 이 속성을 사용할 수 있습니다. 그러나 응용 프로그램에서는 파일에 유지되는 데이터 형식 지정 및 구문 분석과 같이 문화권에 관계없는 필요한 프로세스에만 고정 문화권을 사용해야 합니다. 다른 경우에 이러한 고정 문화권을 사용하면 언어가 잘못되었거나 문화권이 부적합한 결과가 생성될 수 있습니다.

보안 고려 사항

문자열 비교나 대/소문자 변경 결과에 따라 보안을 결정하는 경우 응용 프로그램에서 InvariantCulture를 사용하는 대신 대/소문자를 구분하지 않는 서수 비교를 사용해야 합니다. String.CompareString.ToUpper와 같은 메서드의 기본 구현에서는 CurrentCulture 속성을 사용합니다. 코드에서 문화권별로 문자열 작업을 수행하는 경우 CurrentCulture가 변경되거나 코드가 실행되는 시스템의 문화권이 코드를 테스트하는 데 사용된 문화권과 다르면 보안상 위험할 수 있습니다. 문자열 작업을 작성할 때 예상한 동작이 실행 컴퓨터에서 코드의 실제 동작과 다를 수 있습니다. 반대로 서수 비교는 비교된 문자의 이진 값에만 영향을 받습니다.

문자열 작업

응용 프로그램에서 CurrentCulture 값에 영향을 받지 않는 문화권별 문자열 작업을 수행해야 하는 경우 CultureInfo 매개 변수를 받는 메서드를 사용해야 합니다. 응용 프로그램에서는 이 매개 변수에 InvariantCulture 속성 값을 지정해야 합니다. 응용 프로그램에서는 String.CompareString.ToUpper 등의 메서드에 이 속성을 사용하여 문화권에 관계없이 일정한 결과를 생성할 수 있습니다. InvariantCulture 속성을 사용하여 문화권을 구분하지 않는 문자열 작업을 수행하는 방법에 대한 자세한 내용은 문화권을 구분하지 않는 문자열 작업을 참조하십시오.

데이터 유지

InvariantCulture 속성은 사용자에게 직접 표시되지 않는 데이터를 저장하는 데 유용합니다. 문화권 독립적 형식으로 데이터를 저장하면 변하지 않는 알려진 형식을 유지할 수 있습니다. 다른 문화권의 사용자가 데이터에 액세스할 때 해당 사용자에 맞게 데이터의 형식을 지정할 수 있습니다. 예를 들어 응용 프로그램에서 DateTime 형식을 고정 문화권 형식으로 텍스트 파일에 저장하는 경우 응용 프로그램에서 ToString을 호출하여 문자열을 저장할 때 및 Parse 메서드를 호출하여 문자열을 가져올 때 InvariantCulture 속성을 사용해야 합니다. 이 방법을 사용하면 다른 문화권의 사용자가 데이터를 읽거나 쓸 때 DateTime 형식의 내부 값이 변경되지 않습니다.

다음 코드 예제에서는 빈 문자열("") 또는 InvariantCulture를 사용하여 고정 문화권으로 CultureInfo 개체를 초기화하는 방법을 보여 줍니다.

' The following lines are equivalent.
CultureInfo Invc = New CultureInfo("")
CultureInfo Invc = CultureInfo.InvariantCulture
// The following lines are equivalent.
CultureInfo Invc = New CultureInfo("");
CultureInfo Invc = CultureInfo.InvariantCulture;

다음 코드 예제에서는 ToString 메서드를 사용하여 DateTime 개체를 고정 문화권 형식의 문자열로 파일에 쓰는 방법을 보여 줍니다. 그런 다음 파일에서 고정 문화권 형식으로 문자열을 읽고 Parse 메서드를 사용하여 DateTime 개체로 구문 분석합니다. 그런 다음 "fr-FR" 및 "ja-JP" 문화권에 맞게 DateTime 개체의 형식을 지정하여 표시합니다.

Imports System
Imports System.IO
Imports System.Globalization
Imports Microsoft.VisualBasic

Public Class TextToFile
   Private const FILE_NAME As String = "MyDateFile.txt"   
   
   Public Shared Sub Main()
      If File.Exists(FILE_NAME) Then
         Console.WriteLine("{0} already exists!", FILE_NAME)
         Return
      End If

      Dim sw As StreamWriter = File.CreateText(FILE_NAME)
      
      'Creates a DateTime.
      Dim dtIn As DateTime = DateTime.Now
      Dim InvC As CultureInfo = CultureInfo.InvariantCulture
      ' Writes the string to the file formatted for InvariantCulture.
      sw.WriteLine(dtIn.ToString("d", InvC))
      sw.Close()
      
      If Not File.Exists(FILE_NAME) Then
         Console.WriteLine("{0} does not exist!", FILE_NAME)
         Return
      End If
      
      Dim sr As StreamReader = File.OpenText(FILE_NAME)
      Dim filedate As String
      filedate = sr.Readline()
      While Not filedate Is Nothing
         Console.WriteLine(ControlChars.Newline + "The date stored in _
            the file formatted for the invariant culture is:" + _
            ControlChars.Newline + " {0}", filedate )
         
         ' Creates a new DateTime and parses the 
         ' string stored in the file.
         Dim dtout as DateTime = DateTime.Parse(filedate, InvC)
         
         ' Creates a CultureInfo set to "fr-FR".
         Dim frc As New CultureInfo("fr-FR")
         ' Displays the date formatted for the "fr-FR" culture.
         Console.WriteLine(ControlChars.Newline + "The date read from _
            the file and formatted for the culture ""fr-FR"" is:" + _
            ControlChars.Newline + " {0}", dtout.ToString("d", frc))
         
         ' Creates a CultureInfo set to "ja-JP".
         Dim jpn As New CultureInfo("ja-JP")
         ' Displays the date formatted for the "ja-JP" culture.
         Console.WriteLine(ControlChars.Newline + "The date read from _
            the file and formatted for the culture ""ja-JP"" is:" + _
            ControlChars.Newline + " {0}", dtout.ToString("d", jpn))
        
        filedate = sr.Readline()
      End While
      
      Console.WriteLine(ControlChars.Newline + "The end of the stream _
         has been reached.")
      sr.Close()
   End Sub
End Class
using System;
using System.IO;
using System.Globalization;

public class TextToFile 
{
   private const string FILE_NAME = "MyDateFile.txt";
   public static void Main(String[] args) 
   {
      if (File.Exists(FILE_NAME)) 
      {
         Console.WriteLine("{0} already exists!", FILE_NAME);
         return;
      }
      StreamWriter sw = File.CreateText(FILE_NAME);
      
      // Creates a DateTime.      
      DateTime dtIn = DateTime.Now;
      // Creates a CultureInfo set to InvariantCulture.
      CultureInfo InvC = new CultureInfo("");
      // Converts dt to a string formatted for InvariantCulture,
      // and writes it to a file.
      sw.WriteLine (dtIn.ToString("d",InvC));
      sw.Close();

      if (!File.Exists(FILE_NAME)) 
      {
         Console.WriteLine("{0} does not exist!", FILE_NAME);
         return;
      }
      StreamReader sr = File.OpenText(FILE_NAME);
      String date;
      while ((date=sr.ReadLine())!=null) 
      {
         Console.WriteLine("\nThe date stored in the file formatted for 
               the invariant culture is:\n{0}" , date);    

         // Parses the string stored in the file,
         // and stores it in a DateTime.
         DateTime dtout = DateTime.Parse(date, InvC);

         // Creates a CultureInfo set to "fr-FR".
         CultureInfo frc = new CultureInfo("fr-FR");
         // Displays the date formatted for the "fr-FR" culture.
         Console.WriteLine("\nThe date read from the file and formatted 
               for the culture \"fr-FR\" is:\n{0}" , dtout.ToString("d", 
               frc));

         // Creates a CultureInfo set to "ja-JP".
         CultureInfo jpn= new CultureInfo("ja-JP");
         // Displays the date formatted for the "ja-JP" culture.
         Console.WriteLine("\nThe date read from the file and formatted 
               for the culture \"ja-JP\" is:\n{0}" , dtout.ToString("d", 
               jpn));
      }
      Console.WriteLine ("\nThe end of the stream has been reached.");
      sr.Close();
   }
}

이 코드는 다음과 같이 출력됩니다.

The date stored in the file formatted for the invariant culture is:
07/24/2001

The date read from the file and formatted for the culture "fr-FR" is:
24/07/2001

The date read from the file and formatted for the culture "ja-JP" is:
2001/07/24

The end of the stream has been reached.

참고 항목

개념

CultureInfo 클래스 사용