118

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

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Red Swan
  • 15,157
  • 43
  • 156
  • 238
  • 1
    If the .resx file was added using Visual Studio under the project properties, see [my answer](http://stackoverflow.com/questions/1508570/read-string-from-resx-file-in-c-sharp/18214592#18214592) for an easier and less error prone way to access the string. – Joshcodes Aug 13 '13 at 16:40
  • Have a look at [this](http://snipplr.com/view/2140/csharp-reading-string-from-resource-file--------------------/) link, it should help. – Adriaan Stander Oct 02 '09 at 09:36

15 Answers15

167

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
Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
nathanchere
  • 8,008
  • 15
  • 65
  • 86
84

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");
JeffH
  • 10,254
  • 2
  • 27
  • 48
  • 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. – JeffH Apr 17 '14 at 18:12
  • 1
    items == namespace of the resource file –  Jul 03 '15 at 13:34
  • 10
    poor example: you should explained that items is namespace + root type of the resource – ActiveX Nov 07 '17 at 20:54
  • 2
    You only need `ResourceManager` when you want to load an External resource. Use `.Properties` instead. – Yousha Aleayoub Apr 13 '20 at 12:13
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;
Muru Bakthavachalam
  • 1,340
  • 12
  • 8
  • 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")); – Ian Apr 24 '19 at 10:29
  • 1
    I obtain the following error: 'Resources' does not contain a definition for 'GetString'. – Lechucico Jun 11 '19 at 11:36
  • 1
    You only need `ResourceManager` when you want to load an External resource. Use `.Properties` instead. – Yousha Aleayoub Apr 13 '20 at 12:14
38

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

var <Variable Name> = Properties.Resources.<Resource Name>
SasHok.Tk
  • 477
  • 5
  • 3
  • 4
    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... – Hassan Faghihi Sep 14 '15 at 13:09
  • 3
    Does not work. My resource file is not shown after Properties.Resources."my filename" even if it is set to public – user1804084 Apr 08 '19 at 09:23
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.
DavidC
  • 654
  • 1
  • 14
  • 20
Joshcodes
  • 8,513
  • 5
  • 40
  • 47
20

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"));
Youngjae
  • 24,352
  • 18
  • 113
  • 198
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 "";
   }
AdamantineWolverine
  • 2,131
  • 1
  • 17
  • 14
  • 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();` and use LINQ instead. – Dunc Dec 18 '15 at 11:26
  • 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! – Simone Jul 14 '17 at 07:21
  • Saved my bacon. This should be higher. – NielW Sep 02 '21 at 21:15
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.

Justin Skiles
  • 9,373
  • 6
  • 50
  • 61
  • 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; – emery.noel Jan 24 '17 at 22:04
  • Out of all of the above answers this is the one that made the most sense to me and worked for me. Thanks. – marky Jan 20 '21 at 15:09
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.

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.

Eliezer Miron
  • 388
  • 5
  • 18
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
Nomad77
  • 105
  • 3
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

PRATEEK GHOSH
  • 243
  • 1
  • 15
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

Logan412
  • 109
  • 1
  • 3
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
Miguel Tomás
  • 1,714
  • 1
  • 13
  • 23
1
  1. ResourceFileName.ResourceManager.GetString(ResourceFileName.Name)

2.return Resource.ResponseMsgSuccess;

  • 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](/help/how-to-answer). – Community Dec 10 '21 at 23:04