C# 二进制文件内容写入类BinaryWriter

程序设计界面

C# 二进制文件内容写入类BinaryWriter_第1张图片

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;//新增命名空间

namespace _6005_A_二进制文件内容写入类BinaryWriter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            string msg = "";
            string fileName1 = Application.StartupPath + @"\Kevin.bmp";//源文件
            string fileName2 = Application.StartupPath + @"\KevinCopy.bmp";//目标文件

            byte[] bufByte = null;

            try
            {
                using (FileStream fs1 = new FileStream(fileName1, FileMode.Open))//读取文件到缓冲流
                {
                    if (File.Exists(fileName1))
                    {
                        using (BinaryReader br = new BinaryReader(fs1))//创建缓冲流对应的二进制流
                        {

                            long size = br.BaseStream.Length;
                            bufByte = new byte[size];
                            bufByte = br.ReadBytes((int)size);//br.ReadBytes写入内容到byte数组bufByte中
                            br.Close();
                        }
                        fs1.Close();
                    }
                    else
                    {
                        MessageBox.Show("[" + fileName1 + "]不存在.", "读取失败");
                    }
                }
                using (FileStream fs2 = new FileStream(fileName2, FileMode.Create))
                {
                    using (BinaryWriter bw = new BinaryWriter(fs2))
                    {

                        bw.Write(bufByte);//读取二进制基础流
                        bw.Flush();//写入普通流

                        long newSize = bw.BaseStream.Length;

                        bw.Close();
                        msg = msg + "新文件位置:" + fileName2 + "\n";
                        msg = msg + "新文件大小:" + newSize + " bytes\n";
                        msg = msg + "二进制文件复制完成^.^";
                        MessageBox.Show(msg, "BinaryWriter");

                    }
                    fs2.Close();//生成文件
                }


            }
            catch (IOException ex)
            {

                MessageBox.Show("错误消息:" + ex.Message, "IOException异常");
            }
        }
    }
}

 

你可能感兴趣的:(C#,后端)