- /// <summary>
- /// Return a CSV file in a string.
- /// </summary>
- /// <param name="collection">IList.</param>
- /// <returns>string.</returns>
- public static string CollectionToCsv(IList collection) {
- if (collection == null) throw new ArgumentNullException("collection", "Value can not be null or nothing!");
- StringBuilder sb = new StringBuilder();
- for (int index = 0; index < collection.Count; index++) {
- object item = collection[index];
- if (index == 0) {
- sb.Append(ObjectToCsvHeader(item));
- }
- sb.Append(ObjectToCsvData(item));
- sb.Append(Environment.NewLine);
- }
- return sb.ToString();
- }
- /// <summary>
- /// Creates a comma delimeted string of all the objects property values names.
- /// </summary>
- /// <param name="obj">object.</param>
- /// <returns>string.</returns>
- public static string ObjectToCsvData(object obj) {
- if (obj == null) {
- throw new ArgumentNullException("obj", "Value can not be null or Nothing!");
- }
- StringBuilder sb = new StringBuilder();
- Type t = obj.GetType();
- PropertyInfo[] pi = t.GetProperties();
- for (int index = 0; index < pi.Length; index++) {
- sb.Append(pi[index].GetValue(obj, null));
- if (index < pi.Length - 1) {
- sb.Append(",");
- }
- }
- return sb.ToString();
- }
- /// <summary>
- /// Creates a comma delimeted string of all the objects property names.
- /// </summary>
- /// <param name="obj">object.</param>
- /// <returns>string.</returns>
- public static string ObjectToCsvHeader(object obj) {
- if (obj == null) {
- throw new ArgumentNullException("obj", "Value can not be null or Nothing!");
- }
- StringBuilder sb = new StringBuilder();
- Type t = obj.GetType();
- PropertyInfo[] pi = t.GetProperties();
- for (int index = 0; index < pi.Length; index++) {
- sb.Append(pi[index].Name);
- if (index < pi.Length - 1) {
- sb.Append(",");
- }
- }
- sb.Append(Environment.NewLine);
- return sb.ToString();
- }
Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Objects to CSV
From Wiki
Convert objects into a CSV string
Converts a IList collection into a CSV string. Converts object into a CSV string. Includes headers.
Uses reflection.



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.