1

I want to read files, each of which contains a person's details, as below, and convert it to a Person object.

Covert below

id=1
firstName=John
lastName=Smith

To:

public class Person
{

   public int Id {get;set;}
   public string FirstName{get;set;}
   public string LastName{get;set;}

}

Are there .NET built-in methods to do that, or third party library. I cannot find it via google.

Update:

The file format CANNOT be changed.

1
  • 3
    Did you consider using a more standard data exchange format like JSON ,SEN or XML? Commented Mar 9, 2013 at 14:59

5 Answers 5

3

.NET is really into XML, so you won't find build-in functionality for INI-like formats. But there are a bunch of libs that make it easy to read and write such files, e.g. ini-parser or nini, but you still have to do the mapping to and from objects manually.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Which one is more mature between ini and nini?
nini is much more extensive and propably more mature, but the ini-parser is really straightforward and easy to use. Some basic operations like reading from a file and saving a file are nearly identical in both libs.
1

You could parse the text with String.Split and LINQ:

Dictionary<string, string> dict = text
    .Split(new[] { Environment.NewLine }, StringSplitOptions.None)
    .Select(e => e.Split('='))
    .ToDictionary(strings => strings[0], strings => strings[1]);

Then use something like Dictionary Adapter.

Comments

1

For example using File.ReadAllLines, a little bit of Linq and String.Substring?

var lines = File.ReadAllLines(path).Select(l => l.Trim());
var idLine = lines.FirstOrDefault(l => l.StartsWith("id=", StringComparison.OrdinalIgnoreCase));
var lNameLine = lines.FirstOrDefault(l => l.StartsWith("lastname=", StringComparison.OrdinalIgnoreCase));
var fNameLine = lines.FirstOrDefault(l => l.StartsWith("firstname=", StringComparison.OrdinalIgnoreCase));
if (idLine != null && lNameLine != null && fNameLine != null)
{
    Person person = new Person()
    {
        Id = int.Parse(idLine.Substring(idLine.IndexOf("=") + 1)),
        FirstName = fNameLine.Substring(fNameLine.IndexOf("=") + 1),
        LastName = lNameLine.Substring(lNameLine.IndexOf("=") + 1)
    };
}

(assuming that there's just one person per file)

But i would use a different format like XML (or a database of course).

Comments

0

I really think you should consider changing your input data format into something more standard (like XML or JSON).

But that does not mean you can't read your file at all. You should just read your text file by your own:

var people = new List<Person>();
using (var stream = File.OpenRead("Input.txt"))
{
    using (var reader = new StreamReader(stream))
    {

        while (!reader.EndOfStream)
        {
            int id = int.Parse(reader.ReadLine().Substring(3));
            string firstName = reader.ReadLine().Substring(10);
            string lastName = reader.ReadLine().Substring(9);

            var newPerson = new Person()
            {
                Id = id,
                FirstName = firstName,
                LastName = lastName
            };

            people.Add(newPerson);
        }
    }
}

Comments

-1

If you have the data in a format like this:

<Person>
<Id>1</Id>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Person>

Then this C# code will desrialise into an instance of Person

//assuming you have a string called "data" that contains the above XML.
XDocument xd=XDocument.Parse(data); //needs System.Xml.Linq for XDocument type.
using(var reader = xd.CreateReader())
{
    using(XmlSerializer ser = new XmlSerializer(typeof(Person))
    {
       Person p = ser.Deserialize(reader) as Person;
       //p will be null if it didn't work, so make sure to check it!
    }
}

Note that the deserializer is case sensitive so you need to make sure the element cases match the casing of the properties in your class (You can get arond this by decorating your properties with Serializer attributes that tell the serialzer how to map them here)

The plain native serialzer is great for simple objects like this but can trip you up on some data types like char, bool, etc, so do checkout that link on the attributes.

If you wanted to do it from the format you gave in the question, you'd need to write a custom serialiser, in your case my advice would be to read from your file and generate XML from the data using XDocument Hope that helps.

2 Comments

Would be nice if downvoters could indicate what they feel is wrong about the answer...
The asker clearly indicated that the format is not and can not be XML.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.