Tuesday, December 20, 2011

SharePoint Read Resource File Programatically

SharePoint custom solution development might requires some dynamic or configuration values. Generally the high level configurations can be stored in web.config(Ex: external connection string). But if there are more number of configurations required (Es: List columns, Content type names etc.,) we cannot store them in .config file as it is not safe.

So here the resource file comes into picture. Resource file is XML-Based file which holds the data in key-value pair. Resource file is generally used to store huge configurations for re-usability & consistency and Localization.

Resource file (.resx) should be added to 12\Resources directory in the solution as a new item.
The name format is SampleResourceFile.en-US.resx

If the solution provides provisioning of lists or libraries with multiple columns programatically using either code or xml, All the column names can be stored in Resource file as a Key-Value pair.

Read Resource File: XML
The resource value for a key can be read in XML as below.
Read Resource File: C# Code
The resource value for a key can be read in c# as below.
string customColumnNameKey = SPUtility.GetLocalizedString("$Resources:CustomColumnNameKey", SampleResourceFile, (uint)CultureInfo.CurrentCulture.LCID); //LCIT is current local languare
To read the resource file programatically, a common wrapper class can be created to read the resource file throughout the solution by passing the key.
public class Resources
/// Resource File Name.
/// Filename can be configured in web.configured or can be used as constant.
private const string RESOURCE_FILE_NAME = "SampleResourceFile";

/// Method to get the singleton instance.
public static string GetValue(string key)
return SPUtility.GetLocalizedString("$Resources:" + key, RESOURCE_FILE_NAME, (uint)CultureInfo.CurrentCulture.LCID);

string customColumnName = Resources.GetValue("CustomColumnNameKey");

No comments:

Post a Comment