Click here to Skip to main content
15,065,044 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
<pre lang="xml">/// </summary>
   public class CsvRow : List<string>
   {
       public string LineText { get; set; }
   }

   /// <summary>
   /// Class to write data to a CSV file
   /// </summary>
   public class CsvFileWriter : StreamWriter
   {
       public CsvFileWriter(Stream stream)
           : base(stream)
       {
       }

       public CsvFileWriter(string filename)
           : base(filename)
       {
       }

       /// <summary>
       /// Writes a single row to a CSV file.
       /// </summary>
       /// <param name="row">The row to be written</param>
       public void WriteRow(CsvRow row)
       {
           StringBuilder builder = new StringBuilder();
           bool firstColumn = true;
           foreach (string value in row)
           {
               // Add separator if this isn't the first value
               if (!firstColumn)
                   builder.Append(';');
               // Implement special handling for values that contain comma or quote
               // Enclose in quotes and double up any double quotes
               if (value.IndexOfAny(new char[] {'"', ','}) != -1)
                   builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\""));
               else
                   builder.Append(value);
               firstColumn = false;
           }
           row.LineText = builder.ToString();
           WriteLine(row.LineText,Encoding.UTF8);
       }
   }



C#
using (CsvFileWriter writer = new CsvFileWriter("WriteTest.csv"))
           {


                   for (int j = 0; j < toExcelData.Count; j++)
                   {
                       CsvRow row = new CsvRow();
                       string[] bufzz = toExcelData[j].Split(';');
                       for (int i = 0; i<bufzz.Length; i++)
                       {
                           //for (int h=0; h<)
                           row.Add(bufzz[i]);
                       }
                       writer.WriteRow(row);
                   }


           }


In csv file data in cp-1251 charset. How convert it to utf8
Posted

StreamWriter takes an encoding in its constructor : http://msdn.microsoft.com/en-us/library/system.io.streamwriter.streamwriter.aspx[^]
   
I dont really see why you cant use ReadAllLines/WriteAllLines instead of a stremwriter.
http://msdn.microsoft.com/en-us/library/92e05ft3.aspx[^]

The encoding for writhing files are:
¨http://msdn.microsoft.com/en-us/library/3det53xh.aspx[^]
   
Comments
[no name] 31-Mar-13 13:36pm
   
i want save csv in charset utf with bom

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900