我不确定这里的问题是什么。我的程序可以读取“文本”并将其放在标题中而没有任何问题,但它崩溃并且在它之前不会改变大小或颜色。我试着向同学们寻求帮助,但是他们说我的所有代码都是正确的。
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 :(得分:0)
字段:可能为空,文件结尾? 任何文件打开错误?试图在后台打开时再次打开它?
答案 1 :(得分:0)
更多信息可能会有所帮助。像其他人所说的那样,字段[0] - [2]的值是多少?你收到什么错误?在我看来,你会收到的一个错误是你的索引超出了fields数组的范围......给我们一些更多信息,我们可以更好地帮助你。
答案 2 :(得分:0)
以这种方式试试
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];
}
}
}