2013-05-18 68 views
3

我正在做一個數學測驗,我成功地將我的問題和答案保存在不同的文件中。現在我正試圖從我的文件中加載標籤中的問題。我將加載文件的每一行作爲一個不同的問題。從文件加載錯誤c#

這是我如何保存我的文件:

//checking if question or answer textbox are empty. If they are not then the question is saved 

if (txtquestion.Text != "" & txtanswer.Text != "") { 
    //saves the question in the questions text 
    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\User\Desktop\Assignment 2 Solo part\Questions.txt", true)) { 
    file.WriteLine(txtquestion.Text); 
    } 
    //saves the answer in the answers text 
    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\User\Desktop\Assignment 2 Solo part\Answers.txt", true)) { 
    file.WriteLine(txtanswer.Text); 
    } 
    MessageBox.Show("Question and Answer has been succesfully added in the Quiz!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.None); 
    //cleaning the textboxes for a new question and answer 
    txtanswer.Text = ""; 
    txtquestion.Text = ""; 
} else if (txtquestion.Text == "") 
//checks if the question textbox is empty and shows the corresponding message 
    else if (txtquestion.Text == "") 
    MessageBox.Show("Please enter a question", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    else //checks if the answer textbox is empty and shows the corresponding message 
    if (txtanswer.Text == "") 
     MessageBox.Show("Please enter an answer", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 

這是我正在試圖加載的問題:

private void frmquestion_Load(object sender, EventArgs e) { 
    string line; 
    string[] file = System.IO.File.ReadAllLines(@"C:\Users\User\Desktop\Assignment 2 Solo part\Questions.txt"); 
    line = file.ReadLine(); 
    Console.WriteLine(line); 
} 

我得到的錯誤是:

「 System.Array'沒有包含'ReadLine'的定義,也沒有找到接受類型'System.Array'的第一個參數的擴展方法'ReadLine'(你是否錯過了我們ing指令或程序集引用?)

+0

請記住,@Antreas; 'Array's允許你存儲信息(也可以訪問它,操作它等等),而'System.IO.File'類可以讓你從文件中讀取信息到'Array',或者寫入一個數組到一個文件。看看這些鏈接。 '數組':http://msdn.microsoft.com/en-us/library/system.array.aspx - 'System.IO.File'類:http://msdn.microsoft.com/en-us/ library/system.io.file.aspx –

+1

這是一個有用的鏈接謝謝 –

回答

1

file數組中的每個元素都是文件中的一行。

所以,你應該改變這種代碼:

line = file.ReadLine(); 
Console.WriteLine(line); 

要這樣:

foreach(string line in file) { 
    Console.WriteLine(line); 
} 

這將通過各條線和打印到控制檯。

+0

打敗了我。 +1 –

+1

謝謝!之後,我讓我的標籤改變了它的文字並從行中獲得。它的工作:) –

3

File.ReadAllLines方法將文件的所有行讀入字符串數組。所以你有一串字符串,但是你把它命名爲file,對變量使用有意義的名字會增加代碼的可讀性。

string[] lines = System.IO.File.ReadAllLines(@"C:\Users\User\Desktop\Assignment 2 Solo part\Questions.txt"); 

現在,如果您需要打印每一行,您必須通過字符串數組來循環。

foreach(var line in lines) 
    Console.WriteLine(line); 

一些事情不相關的問題,但對你的編碼

if (txtquestion.Text != "" & txtanswer.Text != "") { 

在這裏,您可以用string.IsNullOrEmpty()方法來檢查空字符串像下面

if (!string.IsNullOrEmpty(txtquestion.Text) && !string.IsNullOrEmpty(txtanswer.Text)) { 

請注意,您需要AND運算符使用&&

+1

好點。謝謝:)現在我會更加小心 –