1

I quite often use Lists to store content as a sort of database. I would create a specific Class that holds a series of propertiesafter which I would export the contents of that list to an external textfile.

For the export I would use something like:

string output = string.empty;
for (int i=0; i<myList.count; i++)
{
   output += myList[i].property1 + ";" + myList[i].property2 + ";" + myList[i].property3 + ";" + myList[i].property4 + ";" + myList[i].property5 + Environtment.NewLine;
}

File.WriteAllText(@"c:\mytextfile.txt", output);

This works like a charm, the only issue is that I have to create an export-routine for every list with a specific class in the application.

I would like to make this a bit more generic in the sense that I would like to create a single export-routine, in which I can pass the name of the List which will then automatically detect the number of parameters in the List and next, export all the different values into the textfile which would have the name of the List.

Something like this pseudo-code:

private void (List selectedList)
{
   for (int i=0; i<selectedList.count; i++)
   {
      output += string.join(";",items) + environment.NewLine;
   }

   File.WriteAllText(filepath + selectedlist + ".txt", output);
}

Does anybody have an idea on how to solve this?

Thank you.

Cainnech
  • 439
  • 1
  • 5
  • 17
  • Possible duplicate of [Using reflection in C# to get properties of a nested object](http://stackoverflow.com/questions/1954746/using-reflection-in-c-sharp-to-get-properties-of-a-nested-object) – Steve Nov 11 '15 at 23:43

1 Answers1

1

To get a list of properties on an object is going to involve using reflection. This is a little rough since I'm not in front of VS at the moment, but if you pass it a List<Foo> it will write a file called Foo.txt

    private const string rootPath = @"C:\Temp\";
    private static void WriteFile<T>(List<T> selectedList)
    {
        var props = typeof(T).GetProperties();
        var sb = new StringBuilder();

        foreach (var item in selectedList) {
            foreach (var prop in props) {
                var val = prop.GetValue(item);
                sb.Append(val);
                sb.Append(";");
            }
        }
        sb.AppendLine();

        var fileName = string.Format("{0}{1}.txt", rootPath, typeof (T).Name);
        File.WriteAllText(fileName, sb.ToString());
    }

Please be aware using reflection can be quite slow. There is plenty of room for optimisation in the above.

Anduril
  • 1,236
  • 1
  • 9
  • 33