tags:

views:

72

answers:

2

Hi

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.

+3  A: 

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.

Henk Holterman
Cannot use XML, file format is determined by third-party.
Captain Comic
That's gonna cause problems if the value part has an '=' in it . . .
Jim Mischel
Nope, neither value nor name part contain '=' character.
Captain Comic
maybe you should specify what 'data' is. I assume a Dictionary<string,string>.
PoweRoy
+3  A: 

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

Callum Rogers
15 rep from 2000! Bring me out of the 1980's!
Callum Rogers
@Callum Rogers: I've got your back! 5 to go!
SnOrfus
OMG OMG OMG. I'll be able to edit everyone's posts! EDIT: Daily rep cap :(
Callum Rogers
at 5k you'll be able to steal passwords, at 10k credit cards numbers
Captain Comic
WARNING: I upvote under the implied agreement that you don't steal my passwords.
SnOrfus