开发者

Simple way to read and write name value text file

开发者 https://www.devze.com 2023-01-17 03:51 出处:网络
I have some class with lots of fields; public class CrowdedHouse { public intvalue1; public floatvalue2; public Guidvalue3;

I have some class with lots of fields;

public class CrowdedHouse
{
  public int     value1;
  public float   value2;
  public Guid    value3;
  public string  Value4;

  // some more fields below
}

My classmust be (de)serialized into simple Windows text file in the following format

NAME1=VALU开发者_StackOverflow中文版E1
NAME2=VALUE2

What is the most convinient way to do that in .NET? This is a text file and all the values must be fist converted to string. Let's assume I have already converted all data to strings.

UPDATE One option would be pinvoke WritePrivateProfileString/WritePrivateProfileString but these are using the required "[Section]" field that I don't need to use.


EDIT: If you have already converted each data value to strings, simply use the method below to serialize it after making a Dictionary of these values:

var dict = new Dictionary<string, string>
{
    { "value1", "value1value" },
    { "value2", "value2value" },
    // etc
}

or use dict.Add(string key, string value).


To read the data, simply split each line around the = and store the results as a Dictionary<string, string>:

string[] lines = File.ReadAllLines("file.ext");
var dict = lines.Select(l => l.Split('=')).ToDictionary(a => a[0], a => a[1]);

To convert a dictionary to the file, use:

string[] lines = dict.Select(kvp => kvp.Key + "=" + kvp.Value).ToArray();
File.WriteAllLines(lines);

Note that your NAMEs and VALUEs cannot contain =.


Writing is easy:

// untested
using (var file = System.IO.File.CreateText("data.txt"))
{
   foreach(var item in data)
      file.WriteLine("{0}={1}", item.Key, item.Value);
}

And for reading it back:

// untested
using (var file = System.IO.File.OpenText("data.txt"))
{
   string line;
   while ((file.ReadLine()) != null)
   {
       string[] parts = line.Split('=');
       string key = parts[0];
       string value = parts[1];
       // use it
   }
}

But probably the best answer is : Use XML.


Minor improvement of Captain Comic answer:

To enable = in values: (will split only once)

var dict = lines.Select(l => l.Split(new[]{'='},2)).ToDictionary(a => a[0], a => a[1]); 
0

精彩评论

暂无评论...
验证码 换一张
取 消