How to export semicolon string to csv value?

I export datagridview entries to a csv file using code:

using (StreamWriter myFile = new StreamWriter(filename, false, Encoding.Default))
{
        string sHeaders = "";
        for (int j = 0; j < dGV.Columns.Count; j++)
        {
             if (dGV.Columns[j].Visible)
             {
                 sHeaders = sHeaders.ToString() + dGV.Columns[j].HeaderText + ", "; 
             }
        }
        myFile.WriteLine(sHeaders);
        // Export data.  
        for (int i = 0; i < dGV.RowCount; i++)
        {
             string stLine = "";
             for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
             {
                 if (dGV.Columns[j].Visible)
                 {
                     stLine = stLine.ToString() + dGV.Rows[i].Cells[j].Value.ToString() + ", ";
                 }
             }
                        myFile.WriteLine(stLine);
        }
     }
  }

But the problem is that the value in the datagridviewcell is Harikrishna, Daxini, then it will not be exported properly, because there is a comma in the cell value, but I need to include the comma in the value. And it must be exported properly. How can i do this? I tried to include this value with double quotes and single quotes, but it does not work.

+3
source share
2 answers

The spaces between the separating commas and the opening double quote may cause problems with the CSV. Replace the type code "val1", "val2"in the csv file "val1","val2". This should solve your problem.

+10

, ",", .

         for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
         {
             if (dGV.Columns[j].Visible)
             {
                  var value = dGV.Rows[i].Cells[j].Value.ToString();
                  var append = value.Contains(",")
                                 ? string.Format("\"{0}\"", value)
                                 : value;
                  stLine = string.Format("{0}{1},", stLine, append) ;
             }
         }
+3

All Articles