C#二进制文件的读写

时间:2024-06-16 14:33:20
sing 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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Random r = new Random();
            byte[] writeArray = new byte[5];
            r.NextBytes(writeArray);
            for (int k = 0; k < 5; k++)
            {
                textBox1.Text += writeArray[k].ToString() + " ";
            }
            // MessageBox.Show("控件已经激活");

            if (textBox1.Text == string.Empty)
            {
                MessageBox.Show("要写入的文件内容不能为空");
            }
            else
            {
                SaveFileDialog SaveFileDialog1 = new SaveFileDialog();
                SaveFileDialog1.Filter = "二进制文件(*.dat)|*.dat";
                if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    FileStream myStream = new FileStream(SaveFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    BinaryWriter myWriter = new BinaryWriter(myStream);
                    myWriter.Write(textBox1.Text);
                    myWriter.Close();
                    myStream.Close();
                    textBox1.Text = string.Empty;
                }
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {

            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "二进制文件(*.dat)|*.dat";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = string.Empty;
                FileStream myStream = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                BinaryReader myReader = new BinaryReader(myStream);
                if (myReader.PeekChar() != -1)
                {
                    textBox1.Text = Convert.ToString(myReader.ReadInt32());
                }
                myReader.Close();
                myStream.Close();
            }
        }
    }
}