C #의 .resx 파일에서 문자열 읽기


99

c #의 .resx 파일에서 문자열을 읽는 방법은 무엇입니까? 나에게 지침을 보내주십시오. 단계적으로


링크를 살펴보면 도움이 될 것입니다.
Adriaan Stander

15
왜? 그들이 내 질문에 만족하지 않으면 왜 잘못된 제안을 받아 들여야합니까?
Red Swan

1
프로젝트 속성에서 Visual Studio를 사용하여 .resx 파일을 추가 한 경우 문자열에 액세스하는 더 쉽고 오류가 발생하기 쉬운 방법에 대한 내 대답 을 참조하십시오 .
Joshcodes 2013-08-13

답변:


75

이 예제는 ResourceManager.GetString ()MSDN 페이지에서 가져온 것입니다 .

// Create a resource manager to retrieve resources.
ResourceManager rm = new ResourceManager("items", Assembly.GetExecutingAssembly());

// Retrieve the value of the string resource named "welcome".
// The resource manager will retrieve the value of the  
// localized resource using the caller's current culture setting.
String str = rm.GetString("welcome");

4
MSDN 페이지에서 참조 : baseName 확장명은 없지만 정규화 된 네임 스페이스 이름을 포함하는 리소스 파일의 루트 이름입니다. 예를 들어 MyApplication.MyResource.en-US.resources라는 리소스 파일의 루트 이름은 MyApplication.MyResource입니다.
JeffH

1
리소스 파일의 항목 == 네임 스페이스

7
좋지 않은 예 : 항목이 네임 스페이스 + 리소스의 루트 유형이라고 설명해야합니다
ActiveX

ResourceManager외부 리소스를로드하려는 경우 에만 필요 합니다. <Namespace>.Properties대신 사용하십시오 .
Yousha Aleayoub

131

ResourceManager외부 리소스 에서로드하지 않는 한 필요하지 않습니다 .
대부분의 경우 프로젝트 (DLL, WinForms 등)를 만들었다 고 가정하면 프로젝트 네임 스페이스, "Resources"및 리소스 식별자 만 사용합니다. 예 :

프로젝트 네임 스페이스 가정 : UberSoft.WidgetPro

그리고 resx에는 다음이 포함됩니다.

resx 콘텐츠 예

다음을 사용할 수 있습니다.

Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED

4
이 답변에 감사드립니다.
Vaishali

1
감사합니다. 답변으로 표시되어야합니다. 이 질문의 "답변"보다 훨씬 명확하고 명확합니다.
Jeroen Jonkman

형식 또는 네임 스페이스가 존재하지 않습니다
폴 맥카시

53

이거 해봐, 나를 위해 일해 .. 간단

리소스 파일 이름이 "TestResource.resx"라고 가정하고 키를 동적으로 전달하려고합니다.

string resVal = TestResource.ResourceManager.GetString(dynamicKeyVal);

네임 스페이스 추가

using System.Resources;

선택적으로 문화를 지정할 수도 있습니다. 기본값과 모순되는 문화 별 출력을 보장하려는 경우 유용합니다. 예 : TestResource.ResourceManager.GetString (description, new CultureInfo ( "en-GB"));
Ian

다음 오류가 발생합니다. 'Resources'에 'GetString'에 대한 정의가 없습니다.
Lechucico

ResourceManager외부 리소스를로드하려는 경우 에만 필요 합니다. <Namespace>.Properties대신 사용하십시오 .
Yousha Aleayoub

29

.resx 파일을 열고 "Access Modifier"를 Public으로 설정합니다.

var <Variable Name> = Properties.Resources.<Resource Name>

2
이 방법은 여러 리소스 파일 (언어)과 함께 작동합니까? 모든 곳에서 ResourceManager 메서드를 사용합니다.이 방법을 사용하여 위험을 감수해야하는지 궁금합니다 ...
deadManN

1
작동하지 않습니다. 내 리소스 파일은 Properties.Resources 후 표시되지 않습니다 "내 이름을"이 공중으로 설정되어있는 경우에도.
user1804084

27

.resx 파일이 Visual Studio를 사용하여 프로젝트 속성 아래에 추가되었다고 가정하면 문자열에 액세스하는 더 쉽고 오류가 발생하기 쉬운 방법이 있습니다.

  1. 솔루션 탐색기에서 .resx 파일을 확장하면 .Designer.cs 파일이 표시됩니다.
  2. .Designer.cs 파일을 열면 속성 네임 스페이스와 내부 클래스가 있습니다. 이 예에서는 클래스 이름이 Resources라고 가정합니다.
  3. 문자열에 액세스하는 것은 다음과 같이 쉽습니다.

    var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager;
    var exampleXmlString = resourceManager.GetString("exampleXml");
  4. JoshCodes.Core.Testing.Unit프로젝트의 기본 네임 스페이스로 바꿉니다 .

  5. "exampleXml"을 문자열 리소스의 이름으로 바꿉니다.

3
매우 유용합니다. 감사.
ejmin

16

@JeffH 답변 다음에 typeof()문자열 어셈블리 이름보다 사용하는 것이 좋습니다 .

    var rm = new ResourceManager(typeof(YourAssembly.Properties.Resources));
    string message = rm.GetString("NameOfKey", CultureInfo.CreateSpecificCulture("ja-JP"));

10

어떤 이유로 리소스 파일을 App_GlobalResources에 넣을 수없는 경우 ResXResourceReader 또는 XML 리더를 사용하여 리소스 파일을 직접 열 수 있습니다.

ResXResourceReader를 사용하기위한 샘플 코드는 다음과 같습니다.

   public static string GetResourceString(string ResourceName, string strKey)
   {


       //Figure out the path to where your resource files are located.
       //In this example, I'm figuring out the path to where a SharePoint feature directory is relative to a custom SharePoint layouts subdirectory.  

       string currentDirectory = Path.GetDirectoryName(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"]));

       string featureDirectory = Path.GetFullPath(currentDirectory + "\\..\\..\\..\\FEATURES\\FEATURENAME\\Resources");

       //Look for files containing the name
       List<string> resourceFileNameList = new List<string>();

       DirectoryInfo resourceDir = new DirectoryInfo(featureDirectory);

       var resourceFiles = resourceDir.GetFiles();

       foreach (FileInfo fi in resourceFiles)
       {
           if (fi.Name.Length > ResourceName.Length+1 && fi.Name.ToLower().Substring(0,ResourceName.Length + 1) == ResourceName.ToLower()+".")
           {
               resourceFileNameList.Add(fi.Name);

           }
        }

       if (resourceFileNameList.Count <= 0)
       { return ""; }


       //Get the current culture
       string strCulture = CultureInfo.CurrentCulture.Name;

       string[] cultureStrings = strCulture.Split('-');

       string strLanguageString = cultureStrings[0];


       string strResourceFileName="";
       string strDefaultFileName = resourceFileNameList[0];
       foreach (string resFileName in resourceFileNameList)
       {
           if (resFileName.ToLower() == ResourceName.ToLower() + ".resx")
           {
               strDefaultFileName = resFileName;
           }

           if (resFileName.ToLower() == ResourceName.ToLower() + "."+strCulture.ToLower() + ".resx")
           {
               strResourceFileName = resFileName;
               break;
           }
           else if (resFileName.ToLower() == ResourceName.ToLower() + "." + strLanguageString.ToLower() + ".resx")
           {
               strResourceFileName = resFileName;
               break;
           }
       }

       if (strResourceFileName == "")
       {
           strResourceFileName = strDefaultFileName;
       }



       //Use resx resource reader to read the file in.
       //https://msdn.microsoft.com/en-us/library/system.resources.resxresourcereader.aspx

       ResXResourceReader rsxr = new ResXResourceReader(featureDirectory + "\\"+ strResourceFileName);         

       //IDictionaryEnumerator idenumerator = rsxr.GetEnumerator();
       foreach (DictionaryEntry d in rsxr)
       {
           if (d.Key.ToString().ToLower() == strKey.ToLower())
           {
               return d.Value.ToString();
           }
       }


       return "";
   }

감사 System.Windows.Forms합니다 System.Resources.ResXResourceReader. 를 사용 하려면에 대한 참조를 추가 해야합니다 . 또한 var enumerator = rsxr.OfType<DictionaryEntry>();LINQ를 대신 사용할 수 있습니다 .
Dunc

resx 파일을 "읽고, 구문 분석하고,로드"하는 방법에 대한 기사 나 게시물을 찾는 것은 매우 어렵습니다. "resx를 프로젝트 문자열의 컨테이너로 사용"하면됩니다. 이 답변에 감사드립니다!
Simone

9

솔루션 / 어셈블리에 리소스 (이름 : ResourceName 및 값 : ResourceValue)를 추가하면 "Properties.Resources.ResourceName"을 사용하여 필요한 리소스를 얻을 수 있습니다.


7

Visual Studio를 통해 .resx 파일을 추가했습니다. 이것은 designer.cs내가 원하는 키의 값을 즉시 반환하는 속성 이있는 파일을 만들었 습니다. 예를 들어, 이것은 디자이너 파일에서 자동 생성 된 코드입니다.

/// <summary>
///   Looks up a localized string similar to When creating a Commissioning change request, you must select valid Assignees, a Type, a Component, and at least one (1) affected unit..
/// </summary>
public static string MyErrorMessage {
    get {
        return ResourceManager.GetString("MyErrorMessage", resourceCulture);
    }
}

이렇게하면 다음과 같이 간단하게 할 수 있습니다.

string message = Errors.MyErrorMessage;

Visual Studio를 통해 생성 ErrorsErrors.resx파일 은 어디에 MyErrorMessage있으며 키입니다.


예, 오늘은 VS2015입니다. 마우스 오른쪽 버튼을 클릭하고 "Resources"파일을 추가하면 모든 키가 "dottable"이됩니다. 따라서 "Script"키가있는 "MyResx.resx"는 문자열 scriptValue = MyResx.Script와 같이 액세스 할 수 있습니다.
emery.noel

5

내 리소스 파일을 내 프로젝트에 직접 추가했기 때문에 resx 파일 이름으로 잘 내부의 문자열에 액세스 할 수있었습니다.

예 : Resource1.resx에서 키 "resourceKey"-> 문자열 "dataString". "dataString"문자열을 얻기 위해 Resource1.resourceKey를 입력합니다.

내가 알지 못하는이 작업을하지 않는 이유가있을 수 있지만 그것은 나를 위해 일했습니다.


3

이를 수행하는 가장 쉬운 방법은 다음과 같습니다.

  1. App_GlobalResources 시스템 폴더를 만들고 여기에 리소스 파일 (예 : Messages.resx)을 추가합니다.
  2. 리소스 파일에 항목을 만듭니다 (예 : ErrorMsg = 오류입니다.
  3. 그런 다음 해당 항목에 액세스하려면 : string errormsg = Resources.Messages.ErrorMsg

2

리소스 파일에서 가치를 얻는 가장 간단한 방법. 프로젝트에 리소스 파일을 추가합니다. 이제 제 경우에는 텍스트 블록 (SilverLight)처럼 추가하려는 문자열을 가져옵니다. 네임 스페이스도 추가 할 필요가 없습니다. 제 경우에는 잘 작동합니다.

txtStatus.Text = Constants.RefractionUpdateMessage;

상수는 프로젝트의 리소스 파일 이름입니다.여기 내 리소스 파일이 어떻게 생겼는지


0

리소스를 검색하려면 리소스 관리자를 만듭니다.

ResourceManager rm = new ResourceManager("param1",Assembly.GetExecutingAssembly());

String str = rm.GetString("param2");

param1 = "AssemblyName.ResourceFolderName.ResourceFileName"

param2 = 리소스 파일에서 검색 할 문자열 이름


0

이것은 나를 위해 작동합니다. 문자열 ok가있는 strings.resx 파일이 있다고 가정합니다. 그것을 읽으려면

String varOk = My.Resources.strings.ok
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.