Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static string SerializeToCSV<T>(this object obj, string delimiter = Delimiters.Comma, IEnumerable<string> ignoredFields = null)
- {
- StringBuilder sb = new StringBuilder();
- int numFieldsAdded = 0;
- int numDelimetersAdded = 0;
- //Get the properties for type T for the headers
- PropertyInfo[] propInfos = typeof(T).GetProperties();
- for (int j = 0; j <= propInfos.Length - 1; j++)
- {
- if (ignoredFields == null || !ignoredFields.Contains(propInfos[j].Name))
- {
- object o = obj.GetType().GetProperty(propInfos[j].Name).GetValue(obj, null);
- if (o != null)
- {
- string value = o.ToString();
- //Check if the value contans a comma and place it in quotes if so
- if (delimiter == Delimiters.Comma && value.Contains(Delimiters.Comma))
- {
- //value = string.Concat("\"", value, "\"");
- value = value.Replace("\"", "\"\"");
- value = string.Concat("\"", value, "\"");
- }
- //Replace any \r or \n special characters from a new line with a space
- if (value.Contains("\r"))
- {
- value = value.Replace("\r", " ");
- }
- if (value.Contains("\n"))
- {
- value = value.Replace("\n", " ");
- }
- sb.Append(value);
- numFieldsAdded++;
- }
- if (j < propInfos.Length - 1)
- {
- sb.Append(delimiter.ToCharArray());
- numDelimetersAdded++;
- }
- }
- }
- string result = sb.ToString();
- if (numDelimetersAdded >= numFieldsAdded && result.EndsWith(delimiter))
- {
- result = result.Substring(0, result.Length - 1);
- }
- return result;
- }
- //helper class
- public static class Delimiters
- {
- public const string Comma = ",";
- public const string Tab = "\t";
- public const string Pipe = "|";
- public const string SemiColon = ";";
- public const string Caret = "^";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement