My Text file format is like; First Raw is header of column
Code
Date/Time;MagazinePos;SampleID;SampleWeight;Moisture;Volatile;Ash;FixedCarbon;Standard;Customer
05-04-2023 15:34:08;1;rcs6737;1.410;3.283;23.761;41.395;31.561;-;HINDALCO
05-04-2023 15:34:08;2;rcs8434;1.100;3.938;26.521;35.089;34.452;-
05-04-2023 15:34:08;3;rcs6630;1.019;4.023;26.570;27.845;41.562;-
05-04-2023 15:34:08;4;rcs8960;1.022;4.266;26.563;33.735;35.436;-
Naimish MakwanaRank #324 · 7.7K reputationPosted Apr 12, 2023, 5:27 AM EDT
Try this:
public DataTable GetDataSourceFromFile(string fileName) { DataTable dt = new DataTable("CreditCards"); string[] columns = null; var lines = File.ReadAllLines(fileName); // assuming the first row contains the columns information if (lines.Count() > 0) { columns = lines[0].Split(new char[] { ',' }); foreach (var column in columns) dt.Columns.Add(column); } // reading rest of the data for (int i = 1; i < lines.Count(); i++) { DataRow dr = dt.NewRow(); string[] values = lines[i].Split(new char[] { ',' }); for (int j = 0; j < values.Count() && j < columns.Count(); j++) dr[j] = values[j]; dt.Rows.Add(dr); } return dt; }Thanks
Rajkiran SwainRank #165 · 14.4K reputationPosted Apr 12, 2023, 5:29 AM EDT
using System; using System.IO; using System.Data; class Program { static void Main(string[] args) { string filePath = "path/to/your/textfile.txt"; // replace with your actual file path char delimiter = ';'; // specify the column delimiter DataTable table = new DataTable(); // read the text file and parse it into a DataTable using (StreamReader reader = new StreamReader(filePath)) { // read the header row and add columns to the table string[] header = reader.ReadLine().Split(delimiter); foreach (string colName in header) { table.Columns.Add(colName); } // read the data rows and add them to the table while (!reader.EndOfStream) { string[] fields = reader.ReadLine().Split(delimiter); table.Rows.Add(fields); } } // print the contents of the DataTable for testing foreach (DataRow row in table.Rows) { foreach (var item in row.ItemArray) { Console.Write($"{item.ToString()}\t"); } Console.WriteLine(); } } }Amit MohantyRank #112 · 20K reputationPosted Apr 12, 2023, 8:07 AM EDT
// Specify the file path string filePath = "C:\\data.txt"; // Create a new DataTable DataTable dt = new DataTable(); // Read the data from the text file string[] lines = File.ReadAllLines(filePath); // Get the header columns string[] headers = lines[0].Split(';'); // Add the columns to the DataTable foreach (string header in headers) { dt.Columns.Add(header); } // Add the data rows to the DataTable for (int i = 1; i < lines.Length; i++) { string[] data = lines[i].Split(';'); DataRow row = dt.NewRow(); for (int j = 0; j < headers.Length; j++) { row[j] = data[j]; } dt.Rows.Add(row); }