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
Awful code, this is a better approach:
ReplyDeletepublic 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.
I have a similar problem, but I am still a beginner. Can you help me out?
DeleteSuppose 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:
5,7,3,6,9,8,3,5,7
5,6,8,3,4,5
6,4,3,2,65,8,6,3,3,5,7,4
4,5,6,78,9,4,2,5,6
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[] { ',' });
}