Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Working with Resource Files in ASP.NET Programatically

0.00/5 (No votes)
12 Nov 2010 1  
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.

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.
 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.

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.

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.

 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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here