2014-05-05 131 views
0

我只想說,我幾周前才加入了stackoverflow,並且每個人都非常有幫助,謝謝。我接下來是我最後兩學期的家庭作業。我現在想要做的是將我保存的數據從我之前編寫的程序導入到文本文件中。基本上文本文件被命名爲「client.txt」和它看起來像這樣C#從文本文件導入數據到文本框

帳號,名字,姓氏的數據,平衡

什麼,我想現在要做的就是寫一個窗口形式,將讀該文本文件中的數據並將其放置到窗體中相應的相應文本框中。這裏是我的代碼到目前爲止,我相信我在正確的軌道上,但我有麻煩,因爲我需要該程序做一個openfiledialog,所以我可以手動選擇client.txt文件,然後導入數據。現在,我得到一個錯誤「就是System.IO.StreamReader不包含一個構造函數參數0」

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.IO; 

namespace Chapter_17_Ex.Sample_2 
{ 
    public partial class Form1 : Form 
    { 
     OpenFileDialog filechooser = new OpenFileDialog(); 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void btnImport_Click(object sender, EventArgs e) 
     { 
      StreamReader fileReader = new StreamReader(); 

      string inputrecord = fileReader.ReadLine(); 
      //string filename; 
      string[] inputfields; 

      if (inputrecord != null) 
      { 
       inputfields = inputrecord.Split(','); 
       txtAccount.Text = inputfields[0]; 
       txtFirstName.Text = inputfields[1]; 
       txtLastName.Text = inputfields[2]; 
       txtBalance.Text = inputfields[3]; 

      } 
      else 
      { 
       MessageBox.Show("End of File"); 
      } 



     } 

     private void btnExit_Click(object sender, EventArgs e) 
     { 
      Application.Exit(); 
     } 
    } 
} 
+0

您需要將文件名傳遞給流讀取器。 – kumaro

+0

是的,這是我在想這個問題是,但由於功課聲明我不得不使用openfiledialog我錯過了什麼地方。 – user3530547

回答

3

要使用你需要構建它傳遞一個StreamReader,至少,文件名讀取。
這可以用在表單全球

// Show the OpenFileDialog and wait for user to close with OK 
    if(filechooser.ShowDialog() == DialogResult.OK) 
    { 
     // Check if the file exists before trying to open it 
     if(File.Exists(filechooser.FileName)) 
     { 
      // Enclose the streamreader in a using block to ensure proper closing and disposing 
      // of the file resource.... 
      using(StreamReader fileReader = new StreamReader(filechooser.FileName)) 
      { 
       string inputrecord = fileReader.ReadLine(); 
       string[] inputfields; 
       .... 
       // The remainder of your code seems to be correct, but a check on the actual 
       // length of the array resulting from the Split call should be added for safety 
      } 
     } 
    } 

注意,無論是OpenFileDialogStreamReader是具有許多特性,不同的方式工作的複雜對象中聲明的變量打開文件對話框來完成。您真的需要查看MSDN文檔中的構造函數和屬性列表以利用它們的全部功能

+0

明白了,非常感謝! – user3530547

相關問題