2014/09/03

How to append, add resource entry to resource .resx file in C#

Notice: You need to add at least Read/Write permisions for NETWORK_SERWICE to .resx file.
// helper class
public class ResEntry
{
public string Entry { get; set; }
public string Message { get; set; }
}
/// <summary>
/// Method adds entries from resourceList to specified language resource file
/// </summary>
/// <param name="resDir">Cathalog where resources are stored</param>
/// <param name="resourceList"></param>
/// <param name="lang">Language prefix fg en - english, pl - polish, etc</param>
public void CreateNewsResourceEntry(string resDir, List<ResEntry> resourceList, string lang)
{
string resxFile = Path.Combine(resDir, "News_." + lang + ".resx");
List<ResEntry> currResList = new List<ResEntry>();
using (ResXResourceReader resxReader = new ResXResourceReader(resxFile))
{
resxReader.UseResXDataNodes = true;
foreach (DictionaryEntry entry in resxReader)
{
var node = (ResXDataNode)entry.Value;
//FileRef is null if it is not a file reference.
if (node.FileRef == null)
{
var value = node.GetValue((ITypeResolutionService)null);
currResList.Add(new ResEntry()
{
Entry = (string)node.Name,
Message = (string)value,
});
}
}
}
currResList.AddRange(resourceList);
using (ResXResourceWriter resx = new ResXResourceWriter(resxFile))
{
foreach (var item in currResList)
resx.AddMetadata(item.Entry, item.Message);
resx.Generate();
}
}
// usage example in ASP.NET
string resDir = Path.Combine(HttpRuntime.AppDomainAppPath, "App_GlobalResources");
List<ResEntry> list = new List<ResEntry>(); in ASP.NET
list.Add(new ResEntry() { Entry = "Title_1", Message = "Title_1" });
list.Add(new ResEntry() { Entry = "Message_1", Message = "Message_2" });
Controller.CreateNewsResourceEntry(resDir, list, "en");
view raw gistfile1.cs hosted with ❤ by GitHub