如何编写资源文件?

3
如果可能从源文件中读取内容,可以像这样操作:
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];

    }
}

那么如何向同一个文件写入内容呢?

4个回答

7
你可以使用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();
   }
}

11
将链接文章的要点包含在回答中并没有错。事实上,从长远来看这使得你的回答更好,因为你永远不知道 MSDN 何时会更改他们的 URL。 - Conrad Frix

1

试试这个

    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();
  }
}

虽然问题是关于如何写入文件,但您的代码似乎正在显示值。 - WorldIsRound

1
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();
            }
        }

我更新了代码,路径应该是你想要写入的文件位置。 - Priyank

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();
                }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接