We can read the CSV file(comma separated file). Following code is used to read the CSV file and store the data into the Dataset.
Namespace part
using System; using System.Data; using System.IO;
Coding part
namespace ConsoleApplication1 { public class Program { static void Main(string[] args) { DataSet myDataSet = GetMyCSVFileData(); foreach (DataColumn MyDataColumn in myDataSet.Tables["MyDataTable"].Columns) { Console.Write("{0,-20}", MyDataColumn.ColumnName); } Console.WriteLine();
foreach (DataRow MyDataRow in myDataSet.Tables["MyDataTable"].Rows) { foreach (DataColumn c in myDataSet.Tables["MyDataTable"].Columns) { Console.Write("{0,-20}", MyDataRow[c]); } Console.WriteLine(); } }
private static DataSet GetMyCSVFileData() { string MystringLine; string[] MystringArray; char[] charArray = new char[] { ',' }; DataSet MyDataSet = new DataSet(); DataTable MyDataTable = MyDataSet.Tables.Add("TheData"); FileStream MyFileStrema = new FileStream("Mycsvfile.txt", FileMode.Open); StreamReader MyStreamReader = new StreamReader(MyFileStrema);
MystringLine = MyStreamReader.ReadLine();
MystringArray = MystringLine.Split(charArray);
for (int i = 0; i <= MystringArray.GetUpperBound(0); i++) { MyDataTable.Columns.Add(MystringArray[i].Trim()); }
MystringLine = MyStreamReader.ReadLine(); while (MystringLine != null) { MystringArray = MystringLine.Split(charArray); DataRow dr = MyDataTable.NewRow(); for (int i = 0; i <= MystringArray.GetUpperBound(0); i++) { dr[i] = MystringArray[i].Trim(); } MyDataTable.Rows.Add(dr); MystringLine = MyStreamReader.ReadLine(); } MyStreamReader.Close(); return MyDataSet; } } }
Code Explanation
1. The method GetMyCSVFileData() is used to read the .CSV file 2. This function read the Mycsvfile.txt file and store the data into the dataset. 3. We can get the data from that dataset. 4. Nowadays many import and export handles the CSV files.
By Nathan
|
No responses found. Be the first to respond and make money from revenue sharing program.
|