Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to read and write name value text file

Tags:

c#

.net

file

text

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=VALUE1
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.

like image 332
Captain Comic Avatar asked Sep 23 '10 19:09

Captain Comic


People also ask

How do I read a text file?

To read from a text fileUse the ReadAllText method of the My. Computer. FileSystem object to read the contents of a text file into a string, supplying the path. The following example reads the contents of test.

How do I extract specific portions of a text file using C#?

ReadLines(@"C:\MyFolder\TextFile. txt") let pieces = line. Split('\t') let date = DateTime. ParseExact(pieces[0] + pieces[1], "MM-dd-yyyyHH:mm:ss", CultureInfo.


1 Answers

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 =.

like image 192
Callum Rogers Avatar answered Oct 03 '22 03:10

Callum Rogers