How do I use the join method to join multiple rows from a file to one string?

+3 votes
asked Jun 1, 2011 by r-lukas

I'm new to C#, so bear with me. I have a text file that I'm loading with one column of numbers. I can load the file and loop through them in the code below, but how can I place them into one string?

file data(each number on separte line,return carriage); 12345 54321 22222

end result; '12345','54321','22222'

private void button1_Click(object sender, EventArgs e)
        int counter = 0;
        string line;
        ArrayList combine = new ArrayList();

        // Read the file and display it line by line.
        System.IO.StreamReader file =
           new System.IO.StreamReader("c:\\test.txt");
        while ((line = file.ReadLine()) != null)
            //just running through so i can see what it's retrieving


        // Suspend the screen.

2 Answers

+2 votes
answered Jun 1, 2011 by brian-rasmussen

Why don't you just use File.ReadAllText. It reads all the lines and returns them as a single string.

+1 vote
answered Jun 1, 2011 by donut

You can use the File.ReadAllLines to put the lines of the file in an array, and String.Join to concatenate these lines. For example:

string[] lines = File.ReadAllLines("C:\\test.txt");
string join = String.Join(" ", lines);

In this example, join will contain all the lines of the file concatenated into a single string, delimited by spaces.
You can use whatever delimiter you wish simply by passing it in as the first argument to String.Join (e.g., if you wanted the lines to be separated by a comma and a space, you'd call String.Join(", ", lines)). Hope this helps.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter