从文件错误c#中加载

本文关键字:加载 错误 文件 | 更新日期: 2023-09-27 18:14:23

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

这是我保存文件的方式:

//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);
}
我得到的错误是:

"系统。Array'没有包含'ReadLine'的定义,也没有扩展方法'ReadLine'接受类型为'System '的第一个参数。Array'可以找到(您是否缺少using指令或程序集引用?)

从文件错误c#中加载

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操作符

使用&&

file数组中的每个元素都是文件中的一行。

所以你应该改变这段代码:
line = file.ReadLine();
Console.WriteLine(line);

:

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

这将遍历每行并将其打印到控制台