Datarow to csv line c #

Is there any form of instruction that converts datarow to a CSV string so that it can be written to a CSV file? (with or without steps in between)

+4
source share
3 answers

A quick google search changed this: http://www.rcs-solutions.com/blog/2009/01/15/ConvertDataTableToCSVViaExtensionMethod.aspx

This is a bit outdated. There is no own way to do this, so you have to either iterate over the data elements using loops, but I would recommend using LINQ methods, since it will be much cleaner.

+1
source

Try with the following code:

StringBuilder sb = new StringBuilder(); var columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray(); sb.AppendLine(string.Join(",", columnNames)); foreach (DataRow row in dt.Rows) { var fields = row.ItemArray.Select(field => field.ToString()).ToArray(); sb.AppendLine(string.Join(",", fields)); } File.WriteAllText("test.csv", sb.ToString()); 
+3
source

I watched this for the day:

According to the quick start, you can write this code:

 [DelimitedRecord(",")] public class Customer { public int CustId; public string Name; public decimal Balance; } FileHelperEngine engine = new FileHelperEngine(typeof(Customer)); Customer[] res = engine.ReadFile("FileIn.txt") as Customer[]; engine.WriteFile("FileOut.txt", res); 
0
source

Source: https://habr.com/ru/post/1400338/


All Articles