【问题标题】:Resource (.resx) data is not saved资源 (.resx) 数据未保存
【发布时间】:2018-10-19 22:40:26
【问题描述】:

我不知道有什么问题。请检查我的代码片段。每次我添加资源数据时,它都会清除最后一个数据并在 .resx 中写入新记录。 例如,Applications.resx 具有“MyApp1”键和“MyApp1Path”值。下次如果我添加带有“MyApp2Path”值的“MyApp2”键,我注意到 {"MyApp1", "MyApp1Path"} 不存在。

//Adding Application in Applications List
ResourceHelper.AddResource("Applications", _appName, _appPath);

这里是 ResourceHelper 类:

public class ResourceHelper
{
    public static void AddResource(string resxFileName, string name, string value)
    {
        using (var resx = new ResXResourceWriter(String.Format(@".\Resources\{0}.resx", resxFileName)))
        {
            resx.AddResource(name, value);
        }
    }
}

【问题讨论】:

    标签: c# resources


    【解决方案1】:

    是的,这是意料之中的,ResXResourceWriter 只是添加节点,而不是追加。

    但是,您可以只读取节点,然后再次添加它们

    public static void AddResource(string resxFileName, string name, object value)
    {
       var fileName = $@".\Resources\{resxFileName}.resx";
    
       using (var writer = new ResXResourceWriter(fileName))
       {
          if (File.Exists(fileName))
          {
             using (var reader = new ResXResourceReader(fileName))
             {
                var node = reader.GetEnumerator();
                while (node.MoveNext())
                {
                   writer.AddResource(node.Key.ToString(), node.Value);
                }
             }
          }
    
          writer.AddResource(name, value);
       }
    }
    

    免责声明,未经测试,可能需要错误检查

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多