-2

How to read in an object by its member variables' names from a text file? For example, I have a class Point with X, Y, Z properties. And I can read a point by

 Z = 1; X = 2; Y = 3;

Or is there any existing libraries to do similar things?

I think I can use Console to read a line or lines and then parse the lines. Is there any pattern or generic templates that I can make it automatic for any class.

user1899020
  • 13,167
  • 21
  • 79
  • 154
  • It is not exactly clear what "read a point by ..." means. Please show a more full example of what you are trying to do. – Scott Chamberlain Mar 07 '16 at 20:06
  • 2
    Json and XML are two standard ways of writing out and reading in data (serialization). – crashmstr Mar 07 '16 at 20:11
  • 1
    It *sounds* like you're trying to deserialize an object from a text file (or just read each "object" line by line?). If so, close your question and look up deserialization. There are many C# examples on this site as well as tutorials on the web to do this. – Michael Todd Mar 07 '16 at 20:12
  • I'm assuming you want to do [this](http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp): `pointInstance.GetType().GetProperty(propNameFromTextFile).GetValue(pointInstance, null)`. – Quantic Mar 07 '16 at 20:12
  • 1
    Possible duplicate of [How to deserialize a string into a class?](http://stackoverflow.com/questions/13708748/how-to-deserialize-a-string-into-a-class) – Eugene Podskal Mar 07 '16 at 20:18

1 Answers1

2

If you can change how object is represented as text (the right term is serialized), I would say that the nearest standarized serialization format to your custom one is YAML.

For example, your object would be serialized as follows:

Point:
   Z: 1
   X: 2
   Y: 3

And there's a serializer/deserializer for .NET called YamlDotNet.

Otherwise, I would go with JSON:

{ z: 1, x: 2, y: 3 }

...which can be deserialized with the well-known and mature JSON.NET library.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206