我正在制作一个程序,可以让你掷出五种不同类型的多边“骰子”,当你掷出一个数字时,我希望它把它存储在一个文本文件中。在我的表单顶部有一个菜单条项目,您可以单击它,它会关闭 StreamWriter 和 FileStream 并打开第二个表单,显示滚动的数字以及滚动的骰子(我只知道滚动的数字现在为简单起见),它显示得很好。但是当我关闭 Reader、Stream 和第二个表单并返回到第一个表单时,我尝试重新打开 Writer 和 Stream,它告诉我已经在使用中。
我的第一个表格的代码:
using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Random ran = new Random();
static FileStream outFile = new FileStream(@"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(outFile);
private int ranNum;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 21);
Display();
}
private void button2_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 13);
Display();
}
private void button3_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 5);
Display();
}
private void button4_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 9);
Display();
}
private void button5_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 11);
Display();
}
private void Display()
{
lblNum.Text = String.Format("{0}", ranNum);
lblNum.Visible = true;
writer.WriteLine(ranNum);
}
private void historyToolStripMenuItem_Click(object sender, EventArgs e)
{
tabControl1.SelectedIndex = 1;
writer.Close();
outFile.Close();
History history = new History();
history.ShowDialog();
}
private void button1_Click_1(object sender, EventArgs e)
{
FileStream outFile = new FileStream(@"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(outFile);
tabControl1.SelectedIndex = 0;
}
}
}
我的第二种形式的代码:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class History : Form
{
public History()
{
InitializeComponent();
}
static private FileStream inFile = new FileStream(@"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.Open, FileAccess.Read);
private StreamReader reader = new StreamReader(inFile);
private void History_Load(object sender, EventArgs e)
{
string item;
item = reader.ReadLine();
try
{
lstHistory.Items.Add(item);
}
catch (Exception)
{
lstHistory.Font = new Font(lstHistory.Font.Name, 12, lstHistory.Font.Unit);
lstHistory.Items.Add("You have not rolled any numbers");
}
}
}
}