Simple way to read and write name value text file
Solution 1
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 NAME
s and VALUE
s cannot contain =
.
Solution 2
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.
Solution 3
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]);
Captain Comic
I am interested in C#, .NET, algorithms, and finance.
Updated on July 06, 2022Comments
-
Captain Comic almost 2 years
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.
-
Jim Mischel over 13 yearsThat's gonna cause problems if the value part has an '=' in it . . .
-
Captain Comic over 13 yearsNope, neither value nor name part contain '=' character.
-
CoreModule over 13 yearsmaybe you should specify what 'data' is. I assume a Dictionary<string,string>.
-
fs_tigre over 6 yearsThis worked for me but I had to modify the writing code, I had to add a second parameter to the
WriteAllLines
method.File.WriteAllLines(@"C:\myFolder\myFile.txt", lines);
Thanks.