2013-12-18 70 views
2

我正在通過C#中的Windows窗體選擇帶有文件夾路徑的文本文件,並收集每個路徑的信息。當時,我可以導入文件並僅顯示文本文件中的第二個路徑,但沒有關於該文件夾的信息。這裏是我的代碼:將每行從文本文件放入數組C#

private void btnFilePath_Click(object sender, EventArgs e) 
    { 
     //creating a stream and setting its value to null 
     Stream myStream = null; 

     //allowing the user select the file by searching for it 
     OpenFileDialog open = new OpenFileDialog(); 
     open.InitialDirectory = "c:\\"; 
     open.Filter = "txt files (*.txt)|*.txt"; 
     open.FilterIndex = 2; 
     open.RestoreDirectory = true; 

     //if statement to print the contents of the file to the text box 
     if (open.ShowDialog() == DialogResult.OK) 
     { 
      try 
      { 
       if ((myStream = open.OpenFile()) != null) 
       { 
        using (myStream) 
        { 
         txtFilePath.Text = string.Format("{0}", open.FileName); 

         if (txtFilePath.Text != "") 
         { 

          lstFileContents.Text = System.IO.File.ReadAllText(txtFilePath.Text); 

          //counting the lines in the text file 
          using (var input = File.OpenText(txtFilePath.Text)) 
          { 
           while (input.ReadLine() != null) 
           { 
             //getting the info 
             lstFileContents.Items.Add("" + pathway); 
             pathway = input.ReadLine(); 
             getSize(); 
             getFiles(); 
             getFolders(); 
             getInfo(); 
            result++; 
           } 

           MessageBox.Show("The number of lines is: " + result, ""); 
           lstFileContents.Items.Add(result); 
          } 

         } 
         else 
         { 
          //display a message box if there is no address 
          MessageBox.Show("Enter a valid address.", "Not a valid address."); 
         } 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Error: Could not read the file from disk. Original error: " + ex.Message); 
      } 
     } 
    } 

我想,使用foreach複製每一行變量或將每個線到一個數組並通過它循環來收集信息。

任何人都可以告訴我哪個是最合適的,所以我可以去MSDN和自己學習,因爲我寧願學習它而不是給代碼。

謝謝!

回答

7

我不知道你的問題是什麼,因爲你似乎已經回答了這個問題。如果你想我們審查它,你的問題是更適合代碼審查:https://codereview.stackexchange.com/

如果你想使用MSDN看這裏:http://msdn.microsoft.com/en-us/library/System.IO.File_methods(v=vs.110).aspx

劇透,這裏是我會怎麼做:

string[] lines = null; 
    try 
    { 
     lines = File.ReadAllLines(path); 
    } 
    catch(Exception ex) 
    { 
     // inform user or log depending on your usage scenario 
    } 

    if(lines != null) 
    { 
     // do something with lines 
    } 
5

只是收集所有的行到數組我會用

var lines = File.ReadAllLines(path); 
相關問題