Read string from .resx file in C#
Asked Answered
C

15

123

How can I read a string from a .resx file in C#?

Call answered 2/10, 2009 at 9:29 Comment(2)
Have a look at this link, it should help.Onepiece
If the .resx file was added using Visual Studio under the project properties, see my answer for an easier and less error prone way to access the string.Hosey
C
86

This example is from the MSDN page on ResourceManager.GetString():

// 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");
Confutation answered 15/10, 2009 at 16:7 Comment(4)
From the MSDN page I referenced:baseName The root name of the resource file without its extension but including any fully qualified namespace name. For example, the root name for the resource file named MyApplication.MyResource.en-US.resources is MyApplication.MyResource.Confutation
items == namespace of the resource fileConception
poor example: you should explained that items is namespace + root type of the resourceOpossum
You only need ResourceManager when you want to load an External resource. Use <Namespace>.Properties instead.Smother
S
170

ResourceManager shouldn't be needed unless you're loading from an external resource.
For most things, say you've created a project (DLL, WinForms, whatever) you just use the project namespace, "Resources" and the resource identifier. eg:

Assuming a project namespace: UberSoft.WidgetPro

And your resx contains:

resx content example

You can just use:

Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED
Stapler answered 10/12, 2012 at 22:4 Comment(2)
The type or namespace does not existArnie
@PaulMcCarthy The .resx probably generated a Designer.cs file. Look for the correct namespace there.Sound
C
86

This example is from the MSDN page on ResourceManager.GetString():

// 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");
Confutation answered 15/10, 2009 at 16:7 Comment(4)
From the MSDN page I referenced:baseName The root name of the resource file without its extension but including any fully qualified namespace name. For example, the root name for the resource file named MyApplication.MyResource.en-US.resources is MyApplication.MyResource.Confutation
items == namespace of the resource fileConception
poor example: you should explained that items is namespace + root type of the resourceOpossum
You only need ResourceManager when you want to load an External resource. Use <Namespace>.Properties instead.Smother
I
68

Try this, works for me.. simple

Assume that your resource file name is "TestResource.resx", and you want to pass key dynamically then,

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

Add Namespace

using System.Resources;
Illjudged answered 19/3, 2014 at 0:48 Comment(3)
You can also optionally specify the Culture - useful if you want to ensure a culture-specific output that contradicts the default. e.g. TestResource.ResourceManager.GetString(description,new CultureInfo("en-GB"));Swen
I obtain the following error: 'Resources' does not contain a definition for 'GetString'.Bug
You only need ResourceManager when you want to load an External resource. Use <Namespace>.Properties instead.Smother
M
38

Open .resx file and set "Access Modifier" to Public.

var <Variable Name> = Properties.Resources.<Resource Name>
Mcfadden answered 16/7, 2012 at 20:50 Comment(2)
does this method work with multiple resource file(languages), cause every where i look they use the ResourceManager Method, and i'm wonder if i should risk using this way, or not...Elaineelam
Does not work. My resource file is not shown after Properties.Resources."my filename" even if it is set to publicAikens
H
33

Assuming the .resx file was added using Visual Studio under the project properties, there is an easier and less error prone way to access the string.

  1. Expanding the .resx file in the Solution Explorer should show a .Designer.cs file.
  2. When opened, the .Designer.cs file has a Properties namespace and an internal class. For this example assume the class is named Resources.
  3. Accessing the string is then as easy as:

    var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager;
    var exampleXmlString = resourceManager.GetString("exampleXml");
    
  4. Replace JoshCodes.Core.Testing.Unit with the project's default namespace.

  5. Replace "exampleXml" with the name of your string resource.
Hosey answered 13/8, 2013 at 16:38 Comment(1)
Very helpful. Thanks.Alainealair
G
21

Followed by @JeffH answer, I recommend to use typeof() than string assembly name.

    var rm = new ResourceManager(typeof(YourAssembly.Properties.Resources));
    string message = rm.GetString("NameOfKey", CultureInfo.CreateSpecificCulture("ja-JP"));
Glyceric answered 13/10, 2014 at 13:28 Comment(0)
B
11

If for some reason you can't put your resources files in App_GlobalResources, then you can open resources files directly using ResXResourceReader or an XML Reader.

Here's sample code for using the 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 "";
   }
Boxthorn answered 27/4, 2015 at 9:15 Comment(3)
Thanks, note that you have to add a reference to System.Windows.Forms to use System.Resources.ResXResourceReader. Also, you can do var enumerator = rsxr.OfType<DictionaryEntry>(); and use LINQ instead.Pshaw
It is very hard to find articles or posts about how to "read, parse and load" a resx file. All you get is "use the resx as the container for the strings of your project". Thank you for this answer!Contort
Saved my bacon. This should be higher.Sloven
S
10

I added the .resx file via Visual Studio. This created a designer.cs file with properties to immediately return the value of any key I wanted. For example, this is some auto-generated code from the designer file.

/// <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);
    }
}

That way, I was able to simply do:

string message = Errors.MyErrorMessage;

Where Errors is the Errors.resx file created through Visual Studio and MyErrorMessage is the key.

Stav answered 3/10, 2014 at 18:23 Comment(2)
Yup I just did this is VS2015 today. Right click, add "Resources" file, and any keys become "dottable". So "MyResx.resx" with a key "Script" can be accessed like string scriptValue = MyResx.Script;Bilious
Out of all of the above answers this is the one that made the most sense to me and worked for me. Thanks.Commutation
O
9

Once you add a resource (Name: ResourceName and Value: ResourceValue) to the solution/assembly, you could simply use "Properties.Resources.ResourceName" to get the required resource.

Orderly answered 17/2, 2016 at 12:52 Comment(0)
H
5

I added my resource file to my project directly, and so I was able to access the strings inside just fine with the resx file name.

Example: in Resource1.resx, key "resourceKey" -> string "dataString". To get the string "dataString", I just put Resource1.resourceKey.

There may be reasons not to do this that I don't know about, but it worked for me.

Hereupon answered 23/7, 2015 at 17:14 Comment(0)
E
3

The easiest way to do this is:

  1. Create an App_GlobalResources system folder and add a resource file to it e.g. Messages.resx
  2. Create your entries in the resource file e.g. ErrorMsg = This is an error.
  3. Then to access that entry: string errormsg = Resources.Messages.ErrorMsg
Epidaurus answered 26/1, 2014 at 16:47 Comment(0)
M
2

The Simplest Way to get value from resource file. Add Resource file in the project. Now get the string where you want to add like in my case it was text block(SilverLight). No need to add any namespace also.Its working fine in my case

txtStatus.Text = Constants.RefractionUpdateMessage;

Constants is my resource file name in the project.Here how my resource file look like

Mahlstick answered 6/3, 2019 at 11:21 Comment(0)
S
1

Create a resource manager to retrieve resources.

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

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

param1 = "AssemblyName.ResourceFolderName.ResourceFileName"

param2 = name of the string to be retrieved from the resource file

Sikorsky answered 13/8, 2019 at 4:45 Comment(0)
A
1

This works for me. say you have a strings.resx file with string ok in it. to read it

String varOk = My.Resources.strings.ok
Adur answered 27/6, 2020 at 17:45 Comment(0)
F
1
  1. ResourceFileName.ResourceManager.GetString(ResourceFileName.Name)

2.return Resource.ResponseMsgSuccess;

Fibroblast answered 10/12, 2021 at 17:30 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Fourlegged

© 2022 - 2024 — McMap. All rights reserved.