Bit Racer

Bit Racer

  • NA
  • 15
  • 589

Export to CSV not working -handheld device-Smart Device App.

Jun 10 2018 11:39 AM
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.
  1. private void btnsubmit_Click(object sender, EventArgs e)  
  2. {  
  3. TextWriter txt = new StreamWriter("logs.txt");  
  4. try  
  5. {  
  6. if (!string.IsNullOrEmpty(txtOutput.Text) && !string.IsNullOrEmpty(txtqty.Text))  
  7. {  
  8. DataTable dt;  
  9. dt = new DataTable();  
  10. dt.Columns.Add("Barcode", System.Type.GetType("System.String"));  
  11. dt.Columns.Add("Location", System.Type.GetType("System.String"));  
  12. dt.Columns.Add("Quantity", System.Type.GetType("System.String"));  
  13. DataRow dr = dt.NewRow();  
  14. dr["Barcode"] = txtOutput.Text.Trim();  
  15. dr["Location"] = "123";  
  16. dr["Quantity"] = txtqty.Text.Trim();  
  17. dt.Rows.Add(dr); StringBuilder data = ConvertDataTableToCsvFile(dt);  
  18. SaveData(data, @"Data.csv"); MessageBox.Show("Data exported Success");  
  19. }  
  20. else  
  21. {  
  22. MessageBox.Show("Please enter all value");  
  23. }  
  24. txt.Close();  
  25. }  
  26. catch (Exception ex)  
  27. {  
  28. string errmsg = ex.Message.ToString();  
  29. MessageBox.Show("error " + errmsg);  
  30. }  
  31. txt.Close();  
  32. }  
  33. public StringBuilder ConvertDataTableToCsvFile(DataTable dtData)  
  34. {  
  35. StringBuilder data = new StringBuilder();  
  36. for (int column = 0;  
  37. column < dtData.Columns.Count; column++)  
  38. {  
  39. //Making sure that end of the line, shoould not have comma delimiter.  
  40. if (column == dtData.Columns.Count - 1) data.Append(dtData.Columns[column].ColumnName.ToString().Replace(","";"));  
  41. else  
  42. data.Append(dtData.Columns[column].ColumnName.ToString().Replace(","";") + ',');  
  43. }  
  44. data.Append(Environment.NewLine);  
  45. //New line after appending columns.  
  46. for (int row = 0; row < dtData.Rows.Count; row++)  
  47. {  
  48. for (int column = 0;  
  49. column < dtData.Columns.Count; column++)  
  50. {  
  51. if (column == dtData.Columns.Count - 1)  
  52. data.Append(dtData.Rows[row][column].ToString().Replace(","";"));  
  53. else  
  54. data.Append(dtData.Rows[row][column].ToString().Replace(","";") + ',');  
  55. }  
  56. if (row != dtData.Rows.Count - 1)  
  57. data.Append(Environment.NewLine);  
  58. }  
  59. return data;  
  60. }  
  61. public void SaveData(StringBuilder data, string filePath)  
  62. {  
  63. using (StreamWriter objWriter = new StreamWriter(filePath))  
  64. {  
  65. objWriter.WriteLine(data); objWriter.Flush();  
  66. }  
  67. }  

Answers (1)