开发者

C#: Simplest way to dump a custom collection to csv file

开发者 https://www.devze.com 2023-04-07 01:35 出处:网络
I have a class public class DevicePatchInfo { public string HostName { get; set; } public string PatchName { get; set; }

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:

  1. Create a StreamWriter with the csv path in the constructor.
  2. Read all property names of the DevicePatchInfo class via reflection and write that as the first line in the csv file.
  3. Enumerate over the List with a foreach.
  4. Read each开发者_运维问答 item in the list and create a string.format with comma separating all item values.
  5. stream.write the new string
  6. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号