【问题标题】:How to write to a resource file?如何写入资源文件?
【发布时间】:2011-08-01 18:18:04
【问题描述】:

如果可以从源文件中读取,像这样:

string fileContent = Resources.Users;

using (var reader = new StringReader(fileContent))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        string[] split = line.Split('|');
        string name = split[0];
        string last = split[1];

    }
}

那你怎么能写入同一个文件呢?

【问题讨论】:

    标签: c# file embedded-resource


    【解决方案1】:
    using System;
    using System.Resources;
    
    using (ResXResourceWriter resx = new ResXResourceWriter(@"D:\project\files\resourcefile.resx"))
                    {
                        resx.AddResource("Key1", "Value");
                        resx.AddResource("Key2", "Value");
                        resx.AddResource("Key3", "Value");
                        
                        resx.Close();
                    }
    

    【讨论】:

      【解决方案2】:
      string path = @"c:\temp\contentfilelocation.extension"; //path to resource file location
      if (!File.Exists(path)) 
      {
          // Create a file to write to.
          using (StreamWriter writer = File.CreateText(path))
                  {
                      string line = "<name>" + "|" + "<last>";
                      writer.WriteLine();
                  }
              }
      

      【讨论】:

      • 我更新了代码,路径应该是你要写入的文件的位置。
      【解决方案3】:

      您可以使用 ResourceWriter 。 我还建议您使用ResourceManager 从文件中读取。

      链接源代码:

      using System;
      using System.Resources;
      
      public class WriteResources {
         public static void Main(string[] args) {
      
        // Creates a resource writer.
        IResourceWriter writer = new ResourceWriter("myResources.resources");
      
        // Adds resources to the resource writer.
        writer.AddResource("String 1", "First String");
      
        writer.AddResource("String 2", "Second String");
      
        writer.AddResource("String 3", "Third String");
      
        // Writes the resources to the file or stream, and closes it.
        writer.Close();
         }
      }
      

      【讨论】:

      • 包含您链接到的文章的重要内容并没有错。事实上,从长远来看,它会让你的答案变得更好,因为你永远不知道 MSDN 什么时候会改变他们的网址
      【解决方案4】:

      试试这个

          class Test {
        public static void Main() {
          ResourceWriter rw = new ResourceWriter("English.resources");
          rw.AddResource("Name", "Test");
          rw.AddResource("Ver", 1.0 );
          rw.AddResource("Author", "www.java2s.com");
          rw.Generate();
          rw.Close();
        }
      }
      

      【讨论】:

      • 以为问题是关于如何写入文件。您的代码似乎正在显示这些值。
      猜你喜欢
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多