Reputation: 1068
I have a class:
public class PicDetailsClass : ISerializable
{
public string Exif_Image_Make { get; set; }
public string Exif_Image_Model { get; set; }
public string Exif_Image_Orientation { get; set;
.....(there are over 200 different strings I want to store in this class)
}
Then I have a text file with the following data:
Exif.Image.Make,ASCII,NIKOND
Exif.Image.Model,ASCII,D5100
...
What I want to do is read the text file, based on the first column (Exif.Image.Make or whatever it is), I want to then store the data from column 3 in the form that is stated in column 2 (ASCII) to a list which I could ultimitly store in a XML or SQL.
I've got the part down where I have created the class like my example above and now reading through the text file line by line, I am able to store each column in a array but not sure how to now store those in a list without doing it one by one using if statements
using (StreamReader reader = new StreamReader(File))
{
string line;
PicDetailsClass Details = new PicDetailsClass();
while ((line = reader.ReadLine()) != null)
{
string allText = Regex.Replace(line, @"\s+", ",");
string[] myString = Regex.Replace(line, @"\s+", ",").Split(',');
foreach (string column in myString)
{
string Type = myString[0];
if (Type == "Exif.Image.Make")
{
Details.Exif_Image_Make = myString[3];
}
}
}
reader.Close();
}
Upvotes: 0
Views: 614
Reputation: 36310
This sounds like something you could fix with some reflection-based magic :-)
As long as the type column matches your property names if you replace . with _ then you can do something like the following (pseudocode from my head):
// Use the following
while ((line = reader.ReadLine()) != null)
{
var allText = Regex.Replace(line, @"\s+", ",");
var myString = Regex.Replace(line, @"\s+", ",").Split(',');
var propertyName = myString[0].Replace(".", "_");
var property = typeof(Details).GetProperty(propertyName);
property.SetValue(Details, myString[3]);
}
This will try to determine the property name by looking at column 0 and replacing . with _. It will then get a reference to the property from the type of the Details object, and finally it will assign the value to the found property.
There is no error checking here, so you will probably add that, and there is no type conversion, but both can easily be added if you need them.
Upvotes: 1