Just Code‎ > ‎

Save DataSet to comma separated file

posted Sep 7, 2009, 12:27 AM by Peter Henell   [ updated Sep 7, 2009, 12:33 AM ]
public static bool SaveComparisonToFile(DataSet ds, string filename, string separator)
    {

        if (ds.Tables[0].Rows.Count > 0)
        {
            try
            {
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filename, false))
                {

                    for (int i = 0; i <= ds.Tables[0].Columns.Count - 1; i++)
                    {

                        writer.Write(ds.Tables[0].Columns[i].ColumnName + separator);
                    }
                    writer.WriteLine();
                    writer.Flush();

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        for (int i = 0; i <= ds.Tables[0].Columns.Count - 1; i++)
                        {
                            writer.Write(row.ItemArray[i].ToString() + separator);
                        }
                        writer.WriteLine();
                        writer.Flush();

                    }
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        return true;
    }
Comments