Jon
Jon

Reputation: 2584

Arrays and text files

I would like to take a text file with a lot of lines and turn it into an array. For example if the text file was:

Line 1

Line 2

Line 3

Line 4`

It would result in

string[] stringList = { "Line 1", "Line 2", "Line 3", "Line 4" };

How do I do this?

I've tried this:

string line;
string[] accountList;
            using (StreamReader file = new StreamReader(accountFileLocation.Text))
            {
                while (line = file.ReadLine() != null)
                {
                    stringList += line;
                }
            }

However that errors with:

Cannot implicitly convert type 'bool' to 'string'

Cannot convert type 'string' to 'string[]'

Cannot implicitly convert type 'string' to 'string[]'

Upvotes: 2

Views: 252

Answers (4)

jonathansamines
jonathansamines

Reputation: 41

Could you try this:

StreamReader reader = new StreamReader();
String content = file.readToEnd();
file.close();
String[] lines = content.split("\n".toCharArray());

Upvotes: 0

penjepitkertasku
penjepitkertasku

Reputation: 562

just try :

string n = "line1\r\nline2\r\n";
string[] list = n.Split('\r'); //or string[] list = n.Split('\n')

Upvotes: 0

user819640
user819640

Reputation: 250

I'll walk you through how I came across the solution as learning what to Google is an important skill in finding solutions.

If you Google 'How to open a text file in c#' you find this webpage http://msdn.microsoft.com/en-us/library/db5x7c0d(v=vs.110).aspx which uses a class called 'StreamReader' and its method 'ReadToEnd()' in an example it gives you.

If you then go on to Google 'c# StreamReader' you can find all of its methods that it has http://msdn.microsoft.com/en-us/library/system.io.streamreader(v=vs.110).aspx

If you scroll down to the R methods you can find one called 'ReadLine'. By clicking into it you can find a working example of exactly what you need: http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline(v=vs.110).aspx

string path = @"c:\temp\MyTest.txt";
 using (StreamReader sr = new StreamReader(path)) 
        {
            while (sr.Peek() >= 0) 
            {
                Console.WriteLine(sr.ReadLine());
            }
        }

Upvotes: 0

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13765

just use

  string[] lines =  File.ReadAllLines(yourpathFile);  

Upvotes: 7

Related Questions