An easy way to read and write a text file with the name

I have a class with many fields;

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

  // some more fields below
}

My class should be (de) serialized to a plain Windows text file in the following format

NAME1=VALUE1
NAME2=VALUE2

What is the most convenient way to do this in .NET? This is a text file and all values ​​must be copied to a string. Suppose I have already converted all the data to strings.

UPDATE One of the options is pinvoke WritePrivateProfileString / WritePrivateProfileString but they use the required "[Section]" field, which I do not need to use.

+3
source share
3 answers

: , Dictionary :

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

dict.Add(string key, string value).


, = Dictionary<string, string>:

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

, :

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

, NAME VALUE =.

+10

:

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

:

// 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
   }
}

, , : XML.

+4

Minor improvement in Captain Comic's answer:

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

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

Source: https://habr.com/ru/post/1766276/


All Articles