Search code examples
c#winformsresx

Add data in resource file(.resx) on the click of button


I want to add data in resource file on the click of button in windows form.
I've a windows form with 3 text boxes -

text_box1: Name
text_box2: Value
text_box3: Comments
and a button named as Save.

I am able to save data in the resource file but not in that way in which I want. It is saving in every value in next row but I want Name comes under Name column, value should came under column, same as for comment.

my code for button click:

private void button1_Click(object sender, EventArgs e)
{
    myMethod.Create(textBox1.Text, textBox2.Text, textBox3.Text);          
}

Code for writing data in resource file:

public class myMethod
{
    public static void Create(string myName, string myValue, string myComment)
    {

        ResXResourceWriter resxWriter;
        try
        {
            resxWriter = new ResXResourceWriter(@"D:\Validator_Tool\resx\resx\myres.resx");
            resxWriter.AddResource("Name", myName);
            resxWriter.AddResource("Value",myValue);
            resxWriter.AddResource("Comment", myComment);
            resxWriter.Close();

        }
        catch (FileNotFoundException caught)
        {
            MessageBox.Show("Source: " + caught.Source + " Message: " + caught.Message);
        }
    }
}

Please help me to append these 3 value in a row not in new row.


Solution

  • Try using ResXDataNode.

    Name and value can be passed to one of its constructor:

    public ResXDataNode(string name, object value)
    

    and comment can be set through the property Comment.

    It is convenient to use object initializer in this case:

    public static void Create(string myName, string myValue, string myComment)
    {
        ResXResourceWriter resxWriter;
        try
        {
            resxWriter = new ResXResourceWriter(@"D:\Validator_Tool\resx\resx\myres.resx");
    
            // --- Use this if it looks more readable and convenient ---
            // var node = new ResXDataNode(myName, myValue);
            // node.Comment = myComment;
            // resxWriter.AddResource(node);
    
            resxWriter.AddResource(new ResXDataNode(myName, myValue)   
            {
                Comment = myComment
            });
    
            resxWriter.Close();
        }
        catch (FileNotFoundException caught)
        {
            MessageBox.Show("Source: " + caught.Source + " Message: " + caught.Message);
        }
    }