2016-03-21 186 views
-3

我有這段代碼,我想改進它。我想刪除轉到無法訪問的代碼

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(); 
} 

我試着使用如果

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(); 
    } 
} 

和喜歡嘗試像這樣使用而

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(); 
} 

但我總是得到一個錯誤這樣做

無法到達的代碼

+6

代碼'繼續;'不執行 - 這是你無法訪問的代碼。 – user1666620

+0

if(r_Read.EndOfStream.Equals(true))break; – Gusman

+0

Goto's是**非常糟糕的做法。我想知道爲什麼這不是第一個評論。 – bytecode77

回答

1

你的問題是在for (; ; i++) 它會永遠增加,爲你的for循環提供一個條件。

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(); 
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; 
    } 
} 
1

你處理文件的方式並不常見。您可以使用循環實現的一切要容易得多:後

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