I'm trying to simply read the whole content of a file and put it in an Array (elements would be lines so array[2] would get the third line, etc).
I tried:
originalFileContentArray = new string[] { fileReader.ReadToEnd() };
Which I believe is a good idea since everything I found abou开发者_StackOverflowt this was big loops to read the file line by line and push it into an array...
The problem with my idea is that the lines does not get separated automatically so the array contains only ONE big element with the whole content in it.
Any idea about how to correctly separate the content into multiple elements?
Thanks!
Use File.ReadAllLines()
instead:
originalFileContentArray = File.ReadAllLines(filePath);
Use String.Split
or File.ReadAllLines()
If you really need to have all of the lines in memory so that you can manipulate them, then File.ReadAllLines is the way to go. But if you just need to process the file line-by-line, then use File.ReadLines:
foreach (string line in File.ReadLines(filename))
{
// process this line
}
Use File.ReadAllLines
originalFileContentArray = fileReader.ReadToEnd().Split(new char[] {'\r'});
I would create an array from a text file like so (each line is an element):
string[] lines = File.ReadAllLines(@"c:\users\" + Environment.UserName + @"\desktop\data.txt");
And then roll through it like so:
foreach (string line in lines) { // manipulate data here }
Let me know if this helps
精彩评论