0

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();
            }
4

1 に答える 1

1

これは、反射ベースの魔法で修正できるもののように思えます:-)

を置き換える場合、タイプ列がプロパティ名と一致する限り。_ を使用すると、次のようなことができます (私の頭からの疑似コード):

// 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]);
}

これは、列 0 を調べて を置き換えることにより、プロパティ名を決定しようとします。と _。次に、Details オブジェクトの型からプロパティへの参照を取得し、最後に見つかったプロパティに値を割り当てます。

ここにはエラー チェックがないため、おそらくそれを追加することになり、型変換はありませんが、両方とも必要に応じて簡単に追加できます。

于 2013-06-19T09:05:32.610 に答える