I'm trying to write key value pairs to my resource file. I'm using code from MSDN (I know that is my first mistake) and after saving the file is full of garbage. I don't have a windows forms project so I don't want to load that namespace. IF I absolutely have to I need a way to avoid runtime errors from that codebase when using the ResXResourceWriter class.
Note, the answer to the similar question does not work.
using (FileStream fs = new FileStream(@"C:\Resource - Copy.resx", FileMode.Open))
using (var w = new ResourceWriter(fs))
{
while (lastKeyIndex > 0)
{
// Code to get key and value strings
w.AddResource(key, value);
}
w.Generate();
}
The output looks something like this in notepad++:
ÎÊï¾ ‘ lSystem.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089#System.Resources.RuntimeResourceSet
PADPADPÛ
_€»b€17sžƒ>·‚šþÑ‚Ç1ƒ¡ºŽƒ(A„‚ß\„” Ö„l–H…1¯…!®b†·C!‡§~f‡üÜ
‰š`w‰vК‰%
... Sometime Later legible but incorrect text and markup...
L a b e l _ C o l o r /* "W o r k u p 2 _ L a b e l _
What is wrong or how is is supposed to work?
EDIT Note: The duplicate question is NOT a duplicate because it is not for the same project type.
This is in an asp.net project. When I add windows forms reference I can compile the application but there is a runtime error on the ResXResourceWriter class.
CS0246: The type or namespace name 'ResXResourceWriter' could not be found (are you missing a using directive or an assembly reference?)
As taffer suggested I used XDocument to handle this situation due to the errors from the ResXResourceWriter class.
I used the code below with a foreach loop around a source of data I needed to bulk insert into my RESX file. I took out the foreach loop for brevity.
The only tricky part is correctly adding the xml:space attribute which is correctly displayed below.
here is how I did it in case anyone else wants to do the same.
XDocument xd;
using (FileStream fs = new FileStream(@"somepath\App_Code\Resource - Copy.resx"
, FileMode.Open, FileAccess.Read))
{
xd = XDocument.Load(fs);
}
XElement elm;
// Loop some data source here and build up your resx file
elm = new XElement("data"
, new XAttribute("name", key)
, new XAttribute(XNamespace.Xml + "space", "preserve")
, new XElement("value", value));
xd.Root.Add(elm);
// end loop
xd.Save(@"somepath\App_Code\Resource - Copy.resx");
Ultimately I used this to leverage the multilanguage app toolkit plugin. I took another developers language file in XAML, loaded all his english into my test project resx file, then used the toolkit to populate all the language files, then wrote a custom app to generate matching XAML files for each language.
It worked well.