从文件加载错误C#
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了从文件加载错误C#,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2510字,纯文字阅读大概需要4分钟。
内容图文
![从文件加载错误C#](/upload/InfoBanner/zyjiaocheng/677/02c82ca29b5f4d2ab34d88be8ba6c4f8.jpg)
我正在进行数学测验,并且已成功将我的问题和答案保存在另一个文件中.现在,我正在尝试从标签中的文件加载问题.我将文件的每一行作为不同的问题加载.
这是我保存文件的方式:
//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方法将文件的所有行读入字符串数组.因此,您具有字符串数组,但将其命名为文件,对变量使用有意义的名称将提高代码的可读性.
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#所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。