gpt4 book ai didi

c# - 从文件加载错误c#

转载 作者:行者123 更新时间:2023-11-30 15:34:04 25 4
gpt4 key购买 nike

我正在做数学测验,我成功地将我的问题和答案保存在不同的文件中。现在我正在尝试将我的问题从我的文件中加载到标签中。我会将文件的每一行加载为一个不同的问题。

这是我保存文件的方式:

//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' does not contain a definition for 'ReadLine' and no extension method 'ReadLine' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)

最佳答案

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 运算符

关于c# - 从文件加载错误c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16621790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com