0

I have a text file :

20160906000001     // header with dateTime = 20160906 and code = 000001
name0100000152255  // body with name = name01 and reference = 00000152255
name0200000152256  // body with name = name02 and reference = 00000152256
name0300000152257  // body with name = name03 and reference = 00000152257

and class :

public class file
{
    public header header { get; set; }

    public List<body> body { get; set; }
}

public class header
{
    public string dateTime { get; set; }

    public string code { get; set; }
}

public class body
{
    public string name { get; set; }

    public string reference { get; set; }
}

I want to create a instance of my class file from the text file :

  • property datetime in header have always 8 chars
  • property code in header have always 6 chars
  • property name in body have always 6 chars
  • property reference in body have always 11 chars

What is the best way to do this?

  • 1
    Use `Substring` to pull out the relevant parts, e.g., `string dateTime = header.Substring(0, 8);`, where `header` is the header line. – Tim Sep 06 '16 at 18:30
  • Use `System.ComponentModel.DataAnnotations` to make sure you have the required length in each string property and then use string manipulations wherever necessary. – Jaya Sep 06 '16 at 18:32
  • You might want to consider parsing the date time into an actual `DateTime` depending on how you want to use your class. And maybe `code` should be an `int` and `reference` should be a `long`. – juharr Sep 06 '16 at 18:35
  • @JS_GodBlessAll how to create a instance of my class with `DataAnnotations` ? –  Sep 06 '16 at 18:39
  • @Azerty123 Not sure what you mean by creating an instance , Here is a link that shows how to decorate the attributes with data annotations http://www.asp.net/mvc/overview/older-versions-1/models-data/validation-with-the-data-annotation-validators-cs. I am assuming you would be deserializing the data or some such. else you need to parse the entire file as text as suggested by Tim to get all attributes then and create an object traditionally using the new operator and assign values to each attribute. – Jaya Sep 06 '16 at 18:44

0 Answers0