开发者

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

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 ArrayL开发者_如何转开发ist();

        // 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)
        {
            Console.WriteLine(line);
            counter++;
            //just running through so i can see what it's retrieving
            MessageBox.Show(line);
        }

        file.Close();

        // Suspend the screen.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜