我想使用二进制读取器/写入器对存储在两个文本文件中的值求和,但是当我运行代码时,它不显示输出,甚至没有异常



的问题定义如下: 我需要设计一个将数字保存到文件的应用程序。单击添加按钮后,它应该执行这些存储数字的相加并显示总和。(使用TextMode(...

namespace exam
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(@"C:UsersMYPCDesktoptrial.txt",FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(textBox1.Text);
bw.Close();
MessageBox.Show("Save to textfilet trial...");
FileStream fs1 = new FileStream(@"C:UsersMYPCDesktoptemp.txt", FileMode.Create);
BinaryWriter bw1 = new BinaryWriter(fs1);
bw1.Write(textBox2.Text);
bw.Close();
MessageBox.Show("Save to textfile.. temp.");

}
private void button2_Click(object sender, EventArgs e)
{
int sum = 0;
FileStream fs = new FileStream(@"C:UsersMYPCDesktoptrial.txt",FileMode.Open);
BinaryReader bw= new BinaryReader(fs);
for (int i = 0; i < 1000; i++)
{
byte[]ar=new byte[500];
while (bw != null)
{
ar[i] = (byte)bw.Read();
sum = ar[i] + ar[i + 1];
}
textBox3.Text = sum.ToString();
}
}
}
}

如果我正确理解您的问题,请尝试以下操作:

private void button1_Click(object sender, EventArgs e)
{
try
{
System.IO.File.WriteAllText(@"C:UsersMYPCDesktoptrial.txt", textBox1.Text);
MessageBox.Show("Save to textfilet trial...");
System.IO.File.WriteAllText(@"C:UsersMYPCDesktoptemp.txt", textBox2.Text);
MessageBox.Show("Save to textfile.. temp.");
}
catch (Exception ex)
{
//LOG>?!
throw ex;
}

}
private void button2_Click(object sender, EventArgs e)
{
try
{
int file1IntVal = int.Parse(System.IO.File.ReadAllText(@"C:UsersMYPCDesktoptrial.txt"));
int file2IntVal = int.Parse(System.IO.File.ReadAllText(@"C:UsersMYPCDesktoptemp.txt"));
textBox3.Text = file1IntVal + file2IntVal;
}
catch (Exception ex)
{
//LOG>?!
throw ex;
}
}

相关内容

最新更新