read string from .resx file in C#

C#.NetString.Net 4.0

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

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;

Solution 4 - C#

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

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

Solution 5 - C#

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.

Solution 6 - C#

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

Solution 7 - C#

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

Solution 8 - C#

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.

Solution 9 - C#

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.

Solution 10 - C#

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.

Solution 11 - C#

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

Solution 12 - C#

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

Solution 13 - C#

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

Solution 14 - C#

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

Solution 15 - C#

  1. ResourceFileName.ResourceManager.GetString(ResourceFileName.Name)

2.return Resource.ResponseMsgSuccess;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRed SwanView Question on Stackoverflow
Solution 1 - C#nathanchereView Answer on Stackoverflow
Solution 2 - C#JeffHView Answer on Stackoverflow
Solution 3 - C#Muru BakthavachalamView Answer on Stackoverflow
Solution 4 - C#SasHok.TkView Answer on Stackoverflow
Solution 5 - C#JoshcodesView Answer on Stackoverflow
Solution 6 - C#YoungjaeView Answer on Stackoverflow
Solution 7 - C#WWCView Answer on Stackoverflow
Solution 8 - C#Justin SkilesView Answer on Stackoverflow
Solution 9 - C#Raghunath RajendrenView Answer on Stackoverflow
Solution 10 - C#Eliezer MironView Answer on Stackoverflow
Solution 11 - C#Nomad77View Answer on Stackoverflow
Solution 12 - C#PRATEEK GHOSHView Answer on Stackoverflow
Solution 13 - C#Logan412View Answer on Stackoverflow
Solution 14 - C#Miguel TomásView Answer on Stackoverflow
Solution 15 - C#VISHNU CHOUDHARYView Answer on Stackoverflow