Windows Phone Developers

Sunday, May 6, 2012

Insert CSV File to Array using C#

Read Text File to Array C#/ Insert CSV File to Array using C# / C# Array from Text/CSV Files
ReadAllLines method can be used to read the contents of a CSV file to array. Each line of the text file will become the elements of the array
public void ReadFile2Array()
String[] FileContent = File.ReadAllLines(@"C:\Temp\vba.csv");
int LineNo = 0;
foreach (string Line in FileContent)
LineNo +=1;
Console.WriteLine("Line " + LineNo.ToString() + " " + Line);
ReadAllLines method opens a text file, reads all lines of the file into a string array, and then closes the file.
The input file is shown below

The output will be like

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon


  1. Awful code, this is a better approach:

    public void ReadFile2Array()
    String[] FileContent = File.ReadAllLines(@"C:\Temp\vba.csv");
    for (int i = 0; i < FileContent.Length; i++)
    Console.WriteLine(String.Format("Line {0} {1}", i+1, FileContent[i]);

    pls don't teach people who are willing to learn such badly optimized and unpractical code.

    1. I have a similar problem, but I am still a beginner. Can you help me out?

      Suppose I have a text file with data like below, I want to read first row and store the elements in one array. Read the second row and store in second array and so on. I will be making some manipulations on the array later on. Can you help me to do this in C#. (I'm a beginner)

      Input text file:





      I would also like to have a loop to go through the arrays to do some manipulations on the elements.

      The Code I am trying out is:

      static void Main(string[] args)
      TextReader tr = new StreamReader("Data.txt");
      // write a line of text to the file
      string word = tr.ReadLine();
      //now split this line into words
      string[] val = word.Split(new Char[] { ',' });