I am trying to read a text file from the hard disk of my computer, and define every line of it as an element of a string array. I can read the file and separate the lines, I just do not know how to put them inside an array. I would be very thankful for your helps!
-
-
I would personally user a List<string> to add the lines to (because we don't know how many lines there will be), and then use the Linq ToArray() method to convert to an array of strings.
(Alternatively, you could keep using the List<string> instead using the array, but it depends on what you're doing with it).
using System.Linq; List<string> myList = new List<string>(); ... // after getting line from file ... myList.Add(lineFromFile); ... // Once whole file read in to list, convert to array. string[] lines = myList.ToArray();
Herbie
-
thanks a lot for answering. it's a very great idea. Liked it.
I myself tried the following code to do the job, but your code is far more simple and better:
using System; using System.IO; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { StreamReader myreader = new StreamReader(@"D:\ekhtera\textFile.txt"); string[] array = new string [arrayDimension(myreader)]; StreamReader reader = new StreamReader(@"D:\ekhtera\textFile.txt"); string line = ""; int index = 0; while (line != null) { line = reader.ReadLine(); if (line != null) array[index] = line; index++; } Console.WriteLine(array[4]); reader.Close(); Console.ReadKey(); } private static int arrayDimension(StreamReader newStream) { string line = ""; int i = 0; while (line != null) { line = newStream.ReadLine(); if (line != null) i++; } newStream.Close(); return i; } } } -
@rezaElc87: It's definitely worth learning about the collection classes in .NET : http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
Herbie
-
In addition, .Net actually has a method for this, File.ReadAllLines:
string[] lines = System.IO.File.ReadAllLines("filename.txt");Just be careful with this if the file can be very large, because the whole array must fit in memory. If you need to process a large file line by line it's better to use StreamReader or File.ReadLines instead without storing the entire file contents in memory.
-
@Sven Groot: That is the ultimate answer. I was actually looking for an answer as simple as this one.
thanks a lot
best regards!
Add your 2¢