c# - Comma escape in stringbuilder -


here's simple issue i'm running into, knowledge limited. have program turns existing database csv; however, many of fields contain commas , need them escape. i've tried couple of things no avail (under objecttocsvdata), included snippet appreciated.

using system; using system.collections.generic; using system.linq; using system.text; using system.collections; using system.reflection;  namespace ofasort { public static class utility {     public static string collectiontocsv(ilist collection)     {         stringbuilder sb = new stringbuilder();              (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();     }      public static string objecttocsvdata(object obj)     {         /*if (obj == null)         {             throw new argumentnullexception("obj", "value null");         }*/         stringbuilder sb = new stringbuilder();          type t = obj.gettype();         propertyinfo[] pi = t.getproperties();         (int index = 0; index < pi.length; index++)         {             /*object otest = pi[index].getvalue(obj, null);             string str = otest.tostring();             sb.append(str.csvquote());             */             sb.append(pi[index].getvalue(obj, null));                     if (index < pi.length - 1)             {                 sb.append(",");             }         }          return sb.tostring();  }      public static string objecttocsvheader(object obj)     {          /*if (obj == null)         {             throw new argumentnullexception("obj", "value null!");         }*/          stringbuilder sb = new stringbuilder();         type t = obj.gettype();         propertyinfo[] pi = t.getproperties();          (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();     }  public static string csvquote(this string text) {     if (text == null)     {         return string.empty;     }      bool containsquote = false;     bool containscomma = false;     int len = text.length;     (int = 0; < len && (containscomma == false || containsquote == false); i++)     {         char ch = text[i];         if (ch == '"')         {             containsquote = true;         }         else if (ch == ',')         {             containscomma = true;         }     }      bool mustquote = containscomma || containsquote;      if (containsquote)     {         text = text.replace("\"", "\"\"");     }      if (mustquote)     {         return "\"" + text + "\"";      }     else     {         return text;     } }  } 

}

public static class csvutility {     // i'm varying bit because think should still work @     // understanding code before copy-pasting. basic premise     // follows:     public static string createfromenumerable(ienumerable enumerable)     {         // create (and store) reference builder. should         // passed around instead of creating one-off instances within         // each method.         var sb = new stringbuilder();         var = 0; // counter          // iterate on each object         ienumerator enumerator = enumerable.getenumerator();         while (enumerator.movenext())         {             // crab current object enumerator             var obj = enumerator.current;              // cache list of properties             var properties = obj.gettype().getproperties();             if (i++ == 0)             {                 // if first item, use properties list ,                 // output heading column.                 // notice how builder passed argument.                 addheading(sb, properties);             }              // every item them dumped usual.             // notice how builder passed argument.             adddata(sb, properties, obj);         }          // return final result string         return sb.tostring();     }      // build heading properties of object     private static void addheading(stringbuilder sb, propertyinfo[] properties)     {         // quick short-circuit check         if (properties == null || properties.length == 0) return;          // iterate on properties         (var p = 0; p < properties.length; p++)         {             // if it's not first property add comma             if (p > 0)             {                 sb.append(",");             }             // add property name, escaping necessary             sb.append(escapevalue(properties[p].name));         }          // add new line (this line complete)         sb.appendline();     }      // build line based on properties , object     private static void adddata(stringbuilder sb, propertyinfo[] properties, object obj)     {         // quick short-circuit check         if (properties == null || properties.length == 0) return;         if (object.referenceequals(obj, null)) return;          // iterate on properties         (var p = 0; p < properties.length; p++)         {             // if it's not first property add comma             if (p > 0)             {                 sb.append(",");             }              // value of property original object             // also, convert string can work it.             var val = properties[p].getvalue(obj).tostring();              // add value, escaping necessary             sb.append(escapevalue(val));         }          // add new line (this line complete)         sb.appendline();     }      // escape value when necessary (per csv standards)     private static string escapevalue(string value)     {         // quick short-circuit check         if (string.isnullorempty(value)) return string.empty;          // if value has comma or quote, need to:         // 1. wrap value in quotations         // 2. convert existing quotations double-quotations         if (value.indexof(',') > -1 || value.indexof('"') > -1)         {             return string.concat("\"", value.replace("\"", "\"\""), "\"");         }          // no modification needed--return as-is.         return value;     } } 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -