I am working with Mobile Handheld device application using c#, trying to export datatable to csv file but none of method are working for me, Plateform Visual Studio 2008 and Smart Device Application.File.WriteALLText method is not working in smart device application.
- private void btnsubmit_Click(object sender, EventArgs e)
- {
- TextWriter txt = new StreamWriter("logs.txt");
- try
- {
- if (!string.IsNullOrEmpty(txtOutput.Text) && !string.IsNullOrEmpty(txtqty.Text))
- {
- DataTable dt;
- dt = new DataTable();
- dt.Columns.Add("Barcode", System.Type.GetType("System.String"));
- dt.Columns.Add("Location", System.Type.GetType("System.String"));
- dt.Columns.Add("Quantity", System.Type.GetType("System.String"));
- DataRow dr = dt.NewRow();
- dr["Barcode"] = txtOutput.Text.Trim();
- dr["Location"] = "123";
- dr["Quantity"] = txtqty.Text.Trim();
- dt.Rows.Add(dr); StringBuilder data = ConvertDataTableToCsvFile(dt);
- SaveData(data, @"Data.csv"); MessageBox.Show("Data exported Success");
- }
- else
- {
- MessageBox.Show("Please enter all value");
- }
- txt.Close();
- }
- catch (Exception ex)
- {
- string errmsg = ex.Message.ToString();
- MessageBox.Show("error " + errmsg);
- }
- txt.Close();
- }
- public StringBuilder ConvertDataTableToCsvFile(DataTable dtData)
- {
- StringBuilder data = new StringBuilder();
- for (int column = 0;
- column < dtData.Columns.Count; column++)
- {
-
- if (column == dtData.Columns.Count - 1) data.Append(dtData.Columns[column].ColumnName.ToString().Replace(",", ";"));
- else
- data.Append(dtData.Columns[column].ColumnName.ToString().Replace(",", ";") + ',');
- }
- data.Append(Environment.NewLine);
-
- for (int row = 0; row < dtData.Rows.Count; row++)
- {
- for (int column = 0;
- column < dtData.Columns.Count; column++)
- {
- if (column == dtData.Columns.Count - 1)
- data.Append(dtData.Rows[row][column].ToString().Replace(",", ";"));
- else
- data.Append(dtData.Rows[row][column].ToString().Replace(",", ";") + ',');
- }
- if (row != dtData.Rows.Count - 1)
- data.Append(Environment.NewLine);
- }
- return data;
- }
- public void SaveData(StringBuilder data, string filePath)
- {
- using (StreamWriter objWriter = new StreamWriter(filePath))
- {
- objWriter.WriteLine(data); objWriter.Flush();
- }
- }