0

i am extracting 4 strings from a text, then i want to create an object with attributes from them, using the first string as the object name and the rest as attributes :

public void Load()
{
    string line = File.ReadAllText(path);
    foreach (var item in line)
    {
        string objectname = line.Split(':', '#')[1];
        string Name = line.Split('$', ':')[2];
        string Number = line.Split(':', '%')[3];
        string Addres = line.Split(':', '&')[4];

        StringBuilder StringBuilder = new StringBuilder();

    }
}

should i use StringBuilder for this? and how?

1
  • StringBuilder is for creating strings, so no. You need to look into serialization. Commented Feb 10, 2013 at 13:24

1 Answer 1

2

If you mean set value of properties based on the dynamic data you can use reflection.

Assuming this is your class:

public class Contact
{
    public string Name { get; set; }
    public string Number { get; set; }
    public string Address { get; set; }
}

And this is possible format of the text file:

Name=John$Address=Canada$Number=111
Number=333$Name=Bob$Address=

Then such code will iterate the lines and create instance of Contact for each, based on the values:

string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
    Contact contact = new Contact();
    string[] parts = line.Split('$');
    foreach (string part in parts)
    {
        string[] temp = part.split('=');
        string propName = temp[0];
        string propValue = (temp.Length > 1) ? temp[1] : "";
        contact.GetType().GetProperty(propName).SetValue(contact, propValue, null);
    }
}

Using this over the above sample two lines will create two instances with the given details.

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

Comments

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.