GUI程序在尝试从文本文件中调用时崩溃
本文关键字:文件 调用 崩溃 文本 程序 GUI | 更新日期: 2023-09-27 18:25:22
我不确定这里有什么问题。我的程序可以毫无问题地读取"文本"并将其放入标题中,但它会崩溃,并且在此之前不会更改大小或颜色。我试着向同学们寻求帮助,但他们说我所有的代码看起来都是正确的。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace RetrieveCustomizedForm
{
public partial class Form1 : Form
{
const char DELIM = ',';
string recordIn;
string[] fields;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
const string FILENAME = "C:''Exercise5''Data.txt";
stuff stuff1 = new stuff();
FileStream inFile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
recordIn = reader.ReadLine();
reader.Close();
inFile.Close();
while (recordIn != null)
{
fields = recordIn.Split(DELIM);
stuff1.color = fields[0];
stuff1.size = fields[1];
stuff1.text = fields[2];
if (fields[0] == "red")
{
this.BackColor = System.Drawing.Color.Red;
}
if (fields[0] == "blue")
{
this.BackColor = System.Drawing.Color.Blue;
}
if (fields[0] == "yellow")
{
this.BackColor = System.Drawing.Color.Yellow;
}
if (fields[1] == "large")
{
this.Size = new System.Drawing.Size(500, 500);
}
if (fields[1] == "small")
{
this.Size = new System.Drawing.Size(300, 300);
}
this.Text = fields[2];
}
}
class stuff
{
public string color { get; set; }
public string size { get; set; }
public string text { get; set; }
}
}
}
字段:可能为空,文件末尾?有文件打开错误吗?当它已经在后台打开时,试图再次打开它?
更多信息可能会有所帮助。正如其他人所说,字段[0]-[2]的值是多少?您收到了哪些错误?在我看来,您将收到的一个错误是,您的索引超出了字段数组的界限。。。给我们一些更多的信息,我们可以更好地帮助你。
这样试试
using (FileStream infile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(infile))
{
string recordIn = reader.ReadLine();
while (recordIn != null)
{
fields = recordIn.Split(DELIM);
stuff1.color = fields[0];
stuff1.size = fields[1];
stuff1.text = fields[2];
if (fields[0] == "red")
{
this.BackColor = System.Drawing.Color.Red;
}
if (fields[0] == "blue")
{
this.BackColor = System.Drawing.Color.Blue;
}
if (fields[0] == "yellow")
{
this.BackColor = System.Drawing.Color.Yellow;
}
if (fields[1] == "large")
{
this.Size = new System.Drawing.Size(500, 500);
}
if (fields[1] == "small")
{
this.Size = new System.Drawing.Size(300, 300);
}
this.Text = fields[2];
}
}
}