Save Dataset To Comma-Delimited File

//save dataset to file

private void saveFile()

{

try

{

saveFileDialog1.Filter = “Text File|*.csv”;

DialogResult dr = saveFileDialog1.ShowDialog();

if (dr.Equals(DialogResult.OK))

{

Stream saveStream = saveFileDialog1.OpenFile();

StreamWriter saveWriter = new StreamWriter(saveStream);

string delim = “”;

foreach (DataColumn c in usmDataSet_LocateEst.qLocateEst.Columns)

{

saveWriter.Write(delim);

saveWriter.Write(c.ColumnName);

delim = “,”;

}

saveWriter.WriteLine();

foreach (DataRow r in usmDataSet_LocateEst.qLocateEst.Rows)

{

delim = “”;

foreach (DataColumn c in usmDataSet_LocateEst.qLocateEst.Columns)

{

saveWriter.Write(delim);

saveWriter.Write(r[c]);

delim = “,”;

}

saveWriter.WriteLine();

}

saveWriter.Close();

MessageBox.Show(“File Saved!”, “Save Results”, MessageBoxButtons.OK, MessageBoxIcon.Information);

}

}

catch (Exception ex)

{

MessageBox.Show(“Error Saving File: “ + ex.Message, “Error!”, MessageBoxButtons.OK, MessageBoxIcon.Error);

}

}