Karuna Sagar
Karuna Sagar

Reputation: 51

how to read data from csv file into C# console Application

using System;
namespace jagged_array
{
class Program
{
static void Main(string[] args)
{
string[][] Members = new string[10][]{
new string[]{"amit","[email protected]",         "9999999999"},
new string[]{"chandu","[email protected]","8888888888"},
new string[]{"naveen","[email protected]", "7777777777"},
new string[]{"ramu","[email protected]",       "6666666666"},
new string[]{"durga","[email protected]",     "5555555555"},
new string[]{"sagar","[email protected]",      "4444444444"},
new string[]{"yadav","[email protected]",    "3333333333"},
new string[]{"suraj","[email protected]",        "2222222222"},
new string[]{"niharika","[email protected]","11111111111"},
new string[]{"anusha","[email protected]",  "0000000000"},
};

for (int i =0; i < Members.Length; i++)
{
System.Console.Write("Name List ({0}):", i + 1);
for (int j = 0; j < Members[i].Length; j++)
{
System.Console.Write(Members[i][j] + "\t");
}
System.Console.WriteLine();
}``
Console.ReadKey();
}
}
}

The above is the code for my C# console program in which i used jagged array and i assigned values manually but now my requirement is 'without assigning manually into array i want the same details to import into my program from an csv file(which is at some location in my disc). So how to do it what functions should i make use , please help me with some example. Thank you.

Upvotes: 4

Views: 21444

Answers (3)

Kevin M
Kevin M

Reputation: 5496

static void Main()
        {
            string csv_file_path=@"C:\Users\Administrator\Desktop\test.csv";

            DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);

            Console.WriteLine("Rows count:" + csvData.Rows.Count);

            Console.ReadLine();
        }


private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
        {
            DataTable csvData = new DataTable();

            try
            {

            using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
                {
                    csvReader.SetDelimiters(new string[] { "," });
                    csvReader.HasFieldsEnclosedInQuotes = true;
                    string[] colFields = csvReader.ReadFields();
                    foreach (string column in colFields)
                    {
                        DataColumn datecolumn = new DataColumn(column);
                        datecolumn.AllowDBNull = true;
                        csvData.Columns.Add(datecolumn);
                    }

                    while (!csvReader.EndOfData)
                    {
                        string[] fieldData = csvReader.ReadFields();
                        //Making empty value as null
                        for (int i = 0; i < fieldData.Length; i++)
                        {
                            if (fieldData[i] == "")
                            {
                                fieldData[i] = null;
                            }
                        }
                        csvData.Rows.Add(fieldData);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return csvData;
        }

Upvotes: 3

Botz3000
Botz3000

Reputation: 39610

I won't go into details, but you can read lines text from a file with File.ReadAllLines.
Once you have those lines, you can split them into parts using String.Split (at least this will work if the CSV file contains very simple information as in your example).

Upvotes: 1

Neil Kennedy
Neil Kennedy

Reputation: 603

Treat the CSV file like an excel workbook and you will find a lot of examples on the web for what you need to do.

ExcelFile ef = new ExcelFile();

// Loads file.
ef.LoadCsv("filename.csv");

// Selects first worksheet.
ExcelWorksheet ws = ef.Worksheets[0];

Upvotes: 1

Related Questions