Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. public static string SerializeToCSV<T>(this object obj, string delimiter = Delimiters.Comma, IEnumerable<string> ignoredFields = null)
  2. {
  3. StringBuilder sb = new StringBuilder();
  4. int numFieldsAdded = 0;
  5. int numDelimetersAdded = 0;
  6. //Get the properties for type T for the headers
  7. PropertyInfo[] propInfos = typeof(T).GetProperties();
  8. for (int j = 0; j <= propInfos.Length - 1; j++)
  9. {
  10. if (ignoredFields == null || !ignoredFields.Contains(propInfos[j].Name))
  11. {
  12. object o = obj.GetType().GetProperty(propInfos[j].Name).GetValue(obj, null);
  13. if (o != null)
  14. {
  15. string value = o.ToString();
  16.  
  17. //Check if the value contans a comma and place it in quotes if so
  18. if (delimiter == Delimiters.Comma && value.Contains(Delimiters.Comma))
  19. {
  20. //value = string.Concat("\"", value, "\"");
  21. value = value.Replace("\"", "\"\"");
  22. value = string.Concat("\"", value, "\"");
  23. }
  24.  
  25. //Replace any \r or \n special characters from a new line with a space
  26. if (value.Contains("\r"))
  27. {
  28. value = value.Replace("\r", " ");
  29. }
  30. if (value.Contains("\n"))
  31. {
  32. value = value.Replace("\n", " ");
  33. }
  34.  
  35. sb.Append(value);
  36. numFieldsAdded++;
  37. }
  38.  
  39. if (j < propInfos.Length - 1)
  40. {
  41. sb.Append(delimiter.ToCharArray());
  42. numDelimetersAdded++;
  43. }
  44. }
  45. }
  46.  
  47. string result = sb.ToString();
  48. if (numDelimetersAdded >= numFieldsAdded && result.EndsWith(delimiter))
  49. {
  50. result = result.Substring(0, result.Length - 1);
  51. }
  52. return result;
  53. }
  54. //helper class
  55. public static class Delimiters
  56. {
  57. public const string Comma = ",";
  58. public const string Tab = "\t";
  59. public const string Pipe = "|";
  60. public const string SemiColon = ";";
  61. public const string Caret = "^";
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement