Click here to Skip to main content
15,881,831 members
Articles / Web Development / ASP.NET

Working with Resource Files in ASP.NET Programatically

Rate me:
Please Sign up or sign in to vote.
4.79/5 (6 votes)
12 Nov 2010CPOL3 min read 53.3K   1.3K   15   16
This article will represent how to work with Resource Files dynamically

Introduction

It is seen sometimes that you need to develop a multilingual website. And for that, you need to maintain resource files (.resx) in ASP.NET. You need to make resource files for each language your website is going to support. But suppose your client wants to make some changes in the text entered in resource files, then what will you do?

Background

I am not going to explain anything about globalization. There are so many articles already well explained on CodeProject which you can refer to.

Using the Code

Here, I am using a BasePage class in which there is a method to return current path of the Resource file which I am using.

C#
protected string CurrentRes
 {
   get
    {
     if (null != Session["SelectResource"])
      {
       if(System.IO.File.Exists(Session["SelectResource"].ToString()))
         {
           return Session["SelectResource"].ToString();
        }
      }
    return Server.MapPath("App_GlobalResources\\Resource.resx");
   }
}

Now inheriting BasePage.cs class to my aspx page will return to me the file path & name. On the page load, I am binding Gridview with resource file as dataset to show user the contents of file.

When user clicks on Insert button, then method insertElement is called which has two parameters Name & Value. Here, a new object of xmldocument is created & xmlnodes are defined. Make sure you inherited System.Xml & System.Resources. Then, I had created a rootnode after loading the XML document.

Following are the steps to be followed:

  1. Create a parent node 'data' with node type as element.
  2. Create an XML attribute 'name'.
  3. Append xmlnode with attributes.
  4. Repeat the same steps if there are child nodes.
  5. Finally, call the saveDoc() method to save your changes in Resource file.
C#
public void insertElement(string name, string value)
   {
       XmlDocument doc = new XmlDocument();
       XmlNode child = null;
       XmlNode xname = null;
       XmlNode rootnode = null;
       doc.Load(FileName);
       rootnode = doc.SelectSingleNode("root");
       xname = doc.CreateNode(XmlNodeType.Element,"data",null);
       XmlAttribute xa =  doc.CreateAttribute("name");
       xa.Value = name;
       XmlAttribute xa1 = doc.CreateAttribute("xml","space",null);
       xa1.Value = "preserve";
       xname.Attributes.Append(xa);
       xname.Attributes.Append(xa1);
       child = doc.CreateNode(XmlNodeType.Element, "value", null);
       child.InnerText = value;
       xname.AppendChild(child);
       rootnode.AppendChild(xname);
      saveDoc(doc, FileName);
   }

SaveDoc method saves the Insertion/ updation operations to the Resource.resx file. SaveDoc takes two arguments document name & path, writes the XML Text to doc file and saves it.

C#
private void saveDoc(XmlDocument doc, string docPath)
{
try
{
   XmlTextWriter writer = new XmlTextWriter(docPath, null);
   writer.Formatting = Formatting.Indented;
   doc.WriteTo(writer);
   writer.Flush();
   writer.Close();
  return;
}
catch{
throw;
  }
} 

In the same way, you can Update the Resource file. Select a record from the Grid. As the Name parameter is always unique, so the resource Value field will get updated. Following is the code snippet for update.

C#
public void updateElement(string name, string value)
{
XmlDocument doc = new XmlDocument();
XmlNode rootnode = null;
doc.Load(FileName);
rootnode = doc.SelectSingleNode("//root");
XmlNode xnode = rootnode.SelectSingleNode("//data[@name='" + name + "']/value");
xnode.InnerText = value;
saveDoc(doc, FileName);
DataBinder();
}

Biding the Grid with Resource File

The following code shows how we can bind the grid with resource file. This solution fits for MVS-2008 or above. Note that in the below code snippet, I am binding only the "data" table from the dataset. The dataset consists of multiple tables like "metadata", "resource", but we only need "data" table. In this way, we can bind the grid with resource file.

C#
private void bindgrid()
   {
     DataSet dsgrid = new DataSet();
     DataTable dt = new DataTable();
     try
       {
           dsgrid.ReadXml(CurrentRes);
           dt.Merge(dsgrid.Tables["data"]);
           dt.AcceptChanges();
           this.grdResource.DataSource = dt;
           this.grdResource.DataBind();

       }
       catch (Exception ex)
       {
           lblMessage.Text = ex.Message;
       }
       finally
       {
           if (dsgrid != null)
           {
               dsgrid.Dispose();
               dsgrid = null;
           }
       }
   }

If you are working in MVS-2005 or lower, you just need to bind grid with dataset.

Points To Be Taken Care Of

Make sure that you don't enter space while making a new entry in the name field as it's a unique field & cannot have a space within. Also be sure that you enter unique Names. Values can be variable or same.

Conclusion

In this article, we have seen how we can manage resource files dynamically to provide user friendly interface to the end users which makes things more clear and easy to handle. Resource files act like the back bone while working with multilingual sites. This opens up numerous possibilities for dynamic and robust systems.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Working in .NET Technologies from the last +11 years and Exploring myself in .NET by learning, implementing and sharing my ideas of latest topics.
For further queries, shoot me a mail at sameersayani@gmail.com

Comments and Discussions

 
QuestionExcellent demo Pin
Member 130079328-Apr-16 1:26
Member 130079328-Apr-16 1:26 
QuestionGetting problem while update resource file. Pin
sunilgoyani17-Apr-15 1:41
sunilgoyani17-Apr-15 1:41 
AnswerRe: Getting problem while update resource file. Pin
Sam_IN2-Jul-15 17:50
Sam_IN2-Jul-15 17:50 
GeneralMy vote of 5 Pin
jitu10jan23-Feb-13 1:33
jitu10jan23-Feb-13 1:33 
GeneralMy vote of 5 Pin
pinkesh_patel5-Mar-11 1:43
pinkesh_patel5-Mar-11 1:43 
GeneralYour New Stuff Works Well in MVS 2010! Pin
pdg7811-Nov-10 8:03
pdg7811-Nov-10 8:03 
GeneralRe: Your New Stuff Works Well in MVS 2010! Pin
Sam_IN12-Nov-10 9:24
Sam_IN12-Nov-10 9:24 
GeneralGetting this to work with asp.net 2.0, MVS 2010, and reader/writer 4.0.0.0 Pin
pdg789-Nov-10 7:27
pdg789-Nov-10 7:27 
GeneralRe: Getting this to work with asp.net 2.0, MVS 2010, and reader/writer 4.0.0.0 Pin
Sam_IN9-Nov-10 21:18
Sam_IN9-Nov-10 21:18 
GeneralRe: Getting this to work with asp.net 2.0, MVS 2010, and reader/writer 4.0.0.0 Pin
pdg7811-Nov-10 7:34
pdg7811-Nov-10 7:34 
GeneralYour gridview only binds with your xml resource file Pin
pdg788-Nov-10 8:22
pdg788-Nov-10 8:22 
GeneralRe: Your gridview only binds with your xml resource file Pin
Sam_IN8-Nov-10 8:42
Sam_IN8-Nov-10 8:42 
GeneralRe: Your gridview only binds with your xml resource file Pin
pdg788-Nov-10 12:59
pdg788-Nov-10 12:59 
GeneralRe: Your gridview only binds with your xml resource file Pin
Sam_IN8-Nov-10 18:24
Sam_IN8-Nov-10 18:24 
GeneralRe: Your gridview only binds with your xml resource file Pin
pdg789-Nov-10 3:56
pdg789-Nov-10 3:56 
GeneralRe: Your gridview only binds with your xml resource file Pin
Sam_IN9-Nov-10 21:18
Sam_IN9-Nov-10 21:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.