Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Become a C# Expert!

Join 148,748 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,702 people online right now. Registration is fast and FREE... Join Now!





Read value from Resource file in C#

This is a snippet you can use to read a certain value from a resource file you have in your application (.resx extension)

Submitted By: PsychoCoder
Actions:
Rating:
Views: 16,095

Language: C#

Last Modified: January 22, 2008
Instructions: Pass the method the name of the file you want to read from, and the key you want the value for and it returns the value

Snippet


  1. //Namespace reference
  2. using System;
  3. using System.Resources;
  4.  
  5.  
  6. #region ReadResourceFile
  7. /// <summary>
  8. /// method for reading a value from a resource file
  9. /// (.resx file)
  10. /// </summary>
  11. /// <param name="file">file to read from</param>
  12. /// <param name="key">key to get the value for</param>
  13. /// <returns>a string value</returns>
  14. public string ReadResourceValue(string file, string key)
  15. {
  16.     //value for our return value
  17.     string resourceValue = string.Empty;
  18.     try
  19.     {
  20.         // specify your resource file name
  21.         string resourceFile = file;
  22.         // get the path of your file
  23.         string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
  24.         // create a resource manager for reading from
  25.         //the resx file
  26.         ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null);
  27.         // retrieve the value of the specified key
  28.         resourceValue = resourceManager.GetString(key);
  29.     }
  30.     catch (Exception ex)
  31.     {
  32.         Console.WriteLine(ex.Message);
  33.         resourceValue = string.Empty;
  34.     }
  35.     return resourceValue;
  36. }
  37. #endregion
  38.  

Copy & Paste


Comments


birendrakumar25 2008-04-24 01:14:29

i am unable to read value of resx file using this method please help me i am calling this method like that string a = s.ReadResourceValue("Default.aspx.en-US.resx", "Label1Resource1.Text"); am i mistaking any where?


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.




Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month