.net 以编程方式修改现有资源文件[重复]

9wbgstp7  于 2023-05-19  发布在  .NET
关注(0)|答案(2)|浏览(250)

此问题已在此处有答案

Modifying .resx file in C#(8个回答)
2天前关闭。
我正在使用以下代码以编程方式生成资源文件。

ResXResourceWriter resxWtr = new ResXResourceWriter(@"C:\CarResources.resx");
resxWtr.AddResource("Title", "Classic American Cars");
resxWtr.Generate();
resxWtr.Close();

现在,我想修改从上面的代码创建的资源文件。如果我使用相同的代码,现有的资源文件将被替换。如何在不丢失现有内容的情况下修改它?

m528fe3b

m528fe3b1#

我有同样的问题,这解决它:
这将附加到现有的.resx文件中

var reader = new ResXResourceReader(@"C:\CarResources.resx");//same fileName
 var node = reader.GetEnumerator();
 var writer = new ResXResourceWriter(@"C:\CarResources.resx");//same fileName(not new)
 while (node.MoveNext())
         {
     writer.AddResource(node.Key.ToString(), node.Value.ToString());
       }
  var newNode = new ResXDataNode("Title", "Classic American Cars");
  writer.AddResource(newNode);
  writer.Generate();
  writer.Close();
xuo3flqw

xuo3flqw2#

这里有一个函数可以帮助您修改资源文件。

public static void UpdateResourceFile(Hashtable data, String path)
{
    Hashtable resourceEntries = new Hashtable();

    //Get existing resources
    ResXResourceReader reader = new ResXResourceReader(path);
    if (reader != null)
    {
        IDictionaryEnumerator id = reader.GetEnumerator();
        foreach (DictionaryEntry d in reader)
        {
            if (d.Value == null)
                resourceEntries.Add(d.Key.ToString(), "");
            else
                resourceEntries.Add(d.Key.ToString(), d.Value.ToString());
        }
        reader.Close();
    }

    //Modify resources here...
    foreach (String key in data.Keys)
    {
        if (!resourceEntries.ContainsKey(key))
        {

            String value = data[key].ToString();
            if (value == null) value = "";

            resourceEntries.Add(key, value);
        }
    }

    //Write the combined resource file
        ResXResourceWriter resourceWriter = new ResXResourceWriter(path);

        foreach (String key in resourceEntries.Keys)
        {
            resourceWriter.AddResource(key, resourceEntries[key]);
        }
        resourceWriter.Generate();
        resourceWriter.Close();

}

参考链接here

相关问题