“foreach(fileInfo 中的 var line)” 仅读取第一行

当我迭代时,我的代码仅生成文本文件的第一行。


我顽固地使用 foreach 循环,但我发现的一切都表明这应该有效。


    public void Button3_Click(object sender, EventArgs e)

    {

        using (OpenFileDialog openFileDialog = new OpenFileDialog())

        {

            openFileDialog.InitialDirectory = "c:\\";

            openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

            openFileDialog.FilterIndex = 2;

            openFileDialog.RestoreDirectory = true;

            DialogResult result = openFileDialog.ShowDialog();

            path = openFileDialog.FileName;

            //checkedTb.Text = fileInfo;

            count = File.ReadLines(path).Count();

            // checkedTb.Text = path;

        }


    }


    public async void StartBtn_Click(object sender, EventArgs e)

    {

        StreamReader reader = new StreamReader(path);

        fileInfo = await reader.ReadLineAsync();


        foreach (var line in fileInfo)

        {

            checkedTb.Text += fileInfo;

        }

    }

我希望它能够读取所有内容,因为这就是“foreach(fileInfo 中的 var line)”的用途。提前感谢大家抽出时间!非常感激!


慕妹3146593
浏览 69回答 2
2回答

隔江千里

目前,您正在迭代一行中的每个字符。如果您想迭代文件中的每一行,您需要类似以下内容:using (var reader = File.OpenText(path)){&nbsp; &nbsp; string line;&nbsp; &nbsp; while ((line = await reader.ReadLineAsync()) != null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Use the line here&nbsp; &nbsp; }}请注意,当前您将每一行附加到checkedTb.Text,没有换行符,因此您最终将获得文件中的所有文本,但在一行中。如果这不是您想要的,您需要准确地弄清楚您想要什么,以便做出适当的改变。目前,在异步代码中使用foreach循环(而不是循环)比较棘手,但在 C# 8 中会变得更容易。您需要返回一个 的东西,如果框架不提供它,您可以自己编写它。(我希望在某个时候有一个方法。)如果您愿意一次性阅读整个文件,那么已经有一个方法- 返回一个. 您可以将其用作:whileIAsyncEnumerable<string>File.ReadLinesAsyncFile.ReadAllLinesAsyncTask<string[]>var lines = await File.ReadAllLinesAsync(path);foreach (var line in lines){&nbsp; &nbsp; ...}但是,如果文件非常大,那么在读取文件时显示进度方面可能不是您想要的。

SMILET

使用 reader.ReadToEndAsync 会更精确,您可以获得文件的所有内容,然后您可以迭代每一行public static async void Click()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; StreamReader reader = new StreamReader(@"D:\Bhushan\a.txt");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var fileContent = await reader.ReadToEndAsync();&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP