I have a class
public class DevicePatchInfo
{
public string HostName { get; set; }
public string PatchName { get; set; }
public bool IsPresent { get; set; }
}
I have a List<DevicePatchInfo>
which is loaded with the data and is bound to a datagrid. I want to press a button and serialize this to a csv file.
The obvious way to do is to:
- Create a StreamWriter with the csv path in the constructor.
- Read all property names of the DevicePatchInfo class via reflection and write that as the first line in the csv file.
- Enumerate over the List with a foreach.
- Read each开发者_运维问答 item in the list and create a string.format with comma separating all item values.
- stream.write the new string
- Dispose streamwriter when all done.
Huf ! Is there any simpler solution to this ? or I should've just typed the code instead of this.
Use the open-source FileHelpers library, which does this for you.
Your proposed solution is almost as close to the metal as you can get. I would suggest you hard-code the headers instead of using reflection, since the class you are writing, DevicePatchInfo
, is well-defined.
精彩评论