[c#] read string from .resx file in C#

How to read the string from .resx file in c#? please send me guidelines . step by step

This question is related to c# .net string .net-4.0

The answer is


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.


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


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

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

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

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

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.


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;

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

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.


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"));

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 "";
   }

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


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.

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to .net-4.0

TLS 1.2 in .NET Framework 4.0 Is it possible to run a .NET 4.5 app on XP? What and When to use Tuple? Fixing slow initial load for IIS Exception: "URI formats are not supported" What is the best way to implement a "timer"? Twitter Bootstrap and ASP.NET GridView How can I convert this foreach code to Parallel.ForEach? "This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded" Differences between .NET 4.0 and .NET 4.5 in High level in .NET