无法访问的代码FOR

时间:2016-03-21 17:26:34

标签: c# loops if-statement for-loop while-loop

我有这个代码,我想改进它。我想删除goto

string NameOfFile = tbOpenFile.Text;

FileStream ReadStream = new FileStream(NameOfFile, FileMode.Open, FileAccess.ReadWrite);

StreamReader r_Read = new StreamReader(ReadStream);
i = 1;
lb1.Items.Clear();

for (; ; i++)
{
    tbOpenFile.Text = r_Read.ReadLine();
    lines[i] = tbOpenFile.Text;

    lb1.Items.Add(lines[i]);

    if (r_Read.EndOfStream.Equals(true)) 
       goto next;
}

next:
{
    textBox2.Text = r_Read.EndOfStream.ToString();
    ReadStream.Close();
}

我尝试使用if

这样做
string NameOfFile = tbOpenFile.Text;
FileStream ReadStream = new FileStream(NameOfFile, FileMode.Open, FileAccess.ReadWrite);

StreamReader r_Read = new StreamReader(ReadStream);
i = 1;

lb1.Items.Clear();

for (; ; i++)
{
    tbOpenFile.Text = r_Read.ReadLine();
    lines[i] = tbOpenFile.Text;

    lb1.Items.Add(lines[i]);

    if (r_Read.EndOfStream.Equals(true)) 
    {
        textBox2.Text = r_Read.EndOfStream.ToString();
        ReadStream.Close();
    }
}

并且喜欢尝试使用while

string NameOfFile = tbOpenFile.Text;
FileStream ReadStream = new FileStream(NameOfFile, FileMode.Open, FileAccess.ReadWrite);

StreamReader r_Read = new StreamReader(ReadStream);
i = 1;

lb1.Items.Clear();

while(r_Read.EndOfStream.Equals(true))
{
    for (; ; i++)
    {
        tbOpenFile.Text = r_Read.ReadLine();
        lines[i] = tbOpenFile.Text;

        lb1.Items.Add(lines[i]);
    }

    continue;

    textBox2.Text = r_Read.EndOfStream.ToString();
    ReadStream.Close();
}

但我总是收到错误

  

无法访问的代码

4 个答案:

答案 0 :(得分:1)

您的问题出在for (; ; i++) 它会永远增加,为你的for循环提供一个条件。

答案 1 :(得分:1)

处理文件的方式并不常见。使用 while 循环可以轻松实现所有目标:

using (StreamReader streamReader = File.OpenText(path))
{
    while (!streamReader.EndOfStream)
    {
        string line = streamReader.ReadLine();
        // Process "line" here...
    }
}

答案 2 :(得分:0)

continue;之后的代码无法执行 - 这是您无法访问的代码。而是在您到达文件末尾时break循环。

尝试以下操作 - 我已经删除了while循环,因为它不是必需的。

StreamReader r_Read = new StreamReader(ReadStream);
i = 1;

lb1.Items.Clear();

for (; ; i++)
{
    tbOpenFile.Text = r_Read.ReadLine();
    lines[i] = tbOpenFile.Text;

    lb1.Items.Add(lines[i]);
    if (r_Read.EndOfStream.Equals(true))
    {
        break; // exits the loop.
    }
}

textBox2.Text = r_Read.EndOfStream.ToString();
ReadStream.Close();

答案 3 :(得分:0)

你需要摆脱循环。

for (; ; i++)
{
    tbOpenFile.Text = r_Read.ReadLine();
    lines[i] = tbOpenFile.Text;

    lb1.Items.Add(lines[i]);

    if (r_Read.EndOfStream.Equals(true)) 
    {
        textBox2.Text = r_Read.EndOfStream.ToString();
        ReadStream.Close();
        break;
    }
}