< Text - file to array >

  • Thread starter Thread starter Carsten Kraft
  • Start date Start date
C

Carsten Kraft

Hello Newsgroup,

I think this is easy for you: I want to save the data line by line into an
string array.

eg.

Text file: Array

Line 1 [0] Line1
Line 2 [1] Line 2
Line 3 [2] Line 3
Line n [3] Line n

How can I do this?
Thankx ...
 
Carsten Kraft said:
I think this is easy for you: I want to save the data line by line into an
string array.

eg.

Text file: Array

Line 1 [0] Line1
Line 2 [1] Line 2
Line 3 [2] Line 3
Line n [3] Line n

How can I do this?

Create an ArrayList.
Open the file with a StreamReader.
Repeatedly call ReadLine, saving the result to the ArrayList until the
result is null.
If you really need an ArrayList rather than an array, use

string[] array = (string[]) arrayList.ToArray(typeof(string));
 
Slurp the whole file, and split it! Be careful if your file is huge
though :)

public static string[] convertLinesIntoArray(string filename) {
TextReader textReader =
new StreamReader(new FileStream(filename, FileMode.Open));
Regex splitter = new Regex(Environment.NewLine);
return splitter.Split(textReader.ReadToEnd());
}
 
Why not just open a StreamReader, read all the contents of the file, and
split on \n.. That'll return a string array, seperated at linebreaks..

/Brian

Jon Skeet said:
Carsten Kraft said:
I think this is easy for you: I want to save the data line by line into an
string array.

eg.

Text file: Array

Line 1 [0] Line1
Line 2 [1] Line 2
Line 3 [2] Line 3
Line n [3] Line n

How can I do this?

Create an ArrayList.
Open the file with a StreamReader.
Repeatedly call ReadLine, saving the result to the ArrayList until the
result is null.
If you really need an ArrayList rather than an array, use

string[] array = (string[]) arrayList.ToArray(typeof(string));
 
Brian Hjøllund said:
Why not just open a StreamReader, read all the contents of the file, and
split on \n.. That'll return a string array, seperated at linebreaks..

That would indeed do it - but you'd also want to get rid of all
occurrences of "\r", probably.
 
Back
Top