How To Read RESX File in C-Sharp






4.38/5 (5 votes)
How to read RESX file in C-Sharp
Introduction
In this article, you will learn how we can read a RESX file in our application using C#. I hope you will like it.
Background
Few days ago, I used a RESX file in my application and I have set some error codes and details in it. It worked like a charm. So I thought of sharing a demo with you of how we can use RESX file in our application.
What RESX File is?
- The .resx resource file format consists of XML entries
- These XML entries specify objects and strings inside XML tags
- It can be easily manipulated
Using the Code
To start with, you need to create a web application. Here, I am using Visual Studio 2012 and C# as the language.
Once you created the application, you need to create a RESX file by clicking the “New Item”.
Now you can see a new file in your solution explorer named Resource1.resx.
So our RESX file is ready, right? Now, we can set some values to that. You can see the values I set to my RESX file in the preceding image.
Now add a web page and go to the code behind by right click+view code. What you need to do next is add needed namespaces. You can find them from the preceding code block.
using System.Reflection;
using System.Resources;
using System.Globalization;
Once it is done, you are ready to go. Please paste the below mentioned code in your page load.
ResourceManager rm = new ResourceManager("UsingRESX.Resource1",
Assembly.GetExecutingAssembly());
String strWebsite = rm.GetString("Website",CultureInfo.CurrentCulture);
String strName = rm.GetString("Name");
form1.InnerText = "Website: " + strWebsite + "--Name: " + strName;
So in the above code block, we are getting the values of “Name
” and “Website
” which we have already set in the RESX file. Cool right?
ResourceManager rm = new ResourceManager("UsingRESX.Resource1",
Assembly.GetExecutingAssembly());
In the above mentioned code block, we are setting our Resource file to the ResourceManager
class. Please note that in UsingRESX.Resource1, UsingRESX
is my project base name and Resource1
is my resource file name. The function GetString
is used to read the resource file properties.
Output
Now it is time to see the output.
Conclusion
I hope someone found this article useful. Please share your valuable thoughts and comments. Your feedback is always welcome.
Thanks in advance. Happy coding!