Search code examples
c#xmlresx

C# How to create and save resx files


Acording to Microsoft Developer Network, resx files can be generated in this way. (http://msdn.microsoft.com/en-us/library/gg418542%28v=vs.110%29.aspx)

using (ResXResourceWriter resx = new ResXResourceWriter("filename.resx"))
  {
     resx.AddResource("KeyString", "ValueString");         
  }
resx.Generate();

However, I cannot find the newly generated resx file. (I thought the generated file was set in the local machine, but it doesn't seem to be there.)

I've been searching for (1) how to check where the generated resx file is, and (2) how to save it into a file folder. (i.e.To save a programmatically generated resx file into a folder, as we can create and save xml files by using "XmlDocument.Save("FileName")" method.)

Here is a part of my coding.

    if (saveFileDialog.ShowDialog() == DialogResult.OK) {
        using (ResXResourceWriter resx = new ResXResourceWriter("resxfile.resx")) {                   

            for (int i = 0; i < rowArray.Length; i++) {                    
                string keyStrings = rowArray[i][Key].ToString();     
                string valueStrings = rowArray[i][Value].ToString();
                resx.AddResource(keystrings, valueStrings);
            }
            resx.Generate();
        }                                     
    }

This doesn't save the resx file which is supposed to be generated from the "for" loop. I'd appreciate it if you would give any insight.


Solution

  • You don't need to specifically call resx.Generate() to create the file (it will be called automatically on Dispose at the end of the using block if you haven't called it manually), but if you do, it should go inside the using block:

    using (ResXResourceWriter resx = new ResXResourceWriter("filename.resx"))
    {
        resx.AddResource("KeyString", "ValueString");
        resx.Generate();
    }  
    

    After this, you can find your .resx file inside your project's bin\Debug or bin\Release folder, depending on the configuration.

    You can also pass a filepath to the constructor to specify a custom file folder, e.g.:

    using (ResXResourceWriter resx = new ResXResourceWriter(@"C:\tmp\sampleResource.resx"))
    {
        resx.AddResource("KeyString", "ValueString");
    }   
    

    In this case, the file will appear in C:\tmp.

    You can also use FileStream to control where and how the resource file is getting created, e.g.:

    using (FileStream fs = new FileStream(@"C:\tmp\MySuperResource.resx", FileMode.Create))
    using (ResXResourceWriter resx = new ResXResourceWriter(fs))
    {
        resx.AddResource("Key1", "Value1");
        resx.AddResource("Key2", "Value2");
        resx.AddResource("Key3", "Value3"); 
    }