C# 如何使用join方法将文件中的多行连接到一个字符串?

C# 如何使用join方法将文件中的多行连接到一个字符串?,c#,C#,我是新来C#的,所以请容忍我。我有一个文本文件,我正在加载一列数字。我可以加载文件并在下面的代码中循环它们,但是如何将它们放在一个字符串中呢 文件数据(分隔行、返回框上的每个数字); 12345 54321 22222 最终结果; ‘12345’、‘54321’、‘22222’ private void button1_Click(object sender, EventArgs e) { int counter = 0; string line;

我是新来C#的,所以请容忍我。我有一个文本文件,我正在加载一列数字。我可以加载文件并在下面的代码中循环它们,但是如何将它们放在一个字符串中呢

文件数据(分隔行、返回框上的每个数字); 12345 54321 22222

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

        file.Close();

        // Suspend the screen.
你为什么不直接用它呢。它读取所有行并将它们作为单个字符串返回。

您可以使用将文件的行放入数组中,并将这些行连接起来。例如:

string[] lines = File.ReadAllLines("C:\\test.txt");
string join = String.Join(" ", lines);
在本例中,
join
将包含连接成单个字符串的文件的所有行,以空格分隔。

只需将其作为第一个参数传递给
String.Join
(例如,如果希望行之间用逗号和空格分隔,则可以调用
String.Join(“,”,line)
)。希望这有帮助

而不是使用ArrayList使用列表或其他容器。您将获得更高的类型安全性,并避免装箱/拆箱(程序可能运行得更快)