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;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            System.IO.Stream fn = System.IO.File.Open(@"C:\a\file.dat", System.IO.FileMode.Create);
            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fn);
            for (int i = 0; i < 10; i++)
            {
                bw.Write(i);
            }
            bw.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            System.IO.Stream fn = System.IO.File.Open(@"C:\a\file.dat", System.IO.FileMode.Open);
            System.IO.BinaryReader br = new System.IO.BinaryReader(fn);
            int i = 0;
            while (true)
            {
                try
                {
                    i = br.ReadInt32();
                    listBox1.Items.Add(i);
                }
                catch (Exception)
                {
                    break;
                }
            }
            br.Close();
            //try
            //{
            //    while (true)
            //        listBox1.Items.Add(br.ReadInt32());
            //}
            //catch
            //{
            //    throw new Exception("فایل به پایان رسیده");
            //}
            //finally
            //{
            //    br.Close();
            //}
        }
    }
}
