C#文件流实现文件复制

来源:互联网 发布:能备案的域名后缀 编辑:程序博客网 时间:2024/05/29 18:10
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;
using System.IO;


namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            if (op.ShowDialog()==DialogResult.OK)
            {
                textBox1.Text = op.FileName;
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog sf = new SaveFileDialog();
            if (sf.ShowDialog()==DialogResult.OK)
            {
                textBox2.Text = sf.FileName;
            }
        }
        
        private void btnStart_Click(object sender, EventArgs e)
        {
            //创建读取流
            FileStream fs = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read, FileShare.Read);
            FileInfo fi = new FileInfo(textBox1.Text);
            byte[] buffer=new byte[1024];    
            long count= 0;
            //创建写入流
            FileStream fsm = new FileStream(textBox2.Text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
            while (true)
            {
                //读取数组
                int len=  fs.Read(buffer, 0, buffer.Length);
                //每次以读取的长度写入
                fsm.Write(buffer, 0, len);
                count += len;
                long p = (count * 100) / fi.Length;
                progressBar1.Value = (int)p;
                //如果没有读取到内容,跳出循环
                if (len==0)
                {
                  break;  
                }
            }
           fs.Close();
           fsm.Close();


            


            
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            
            
        }


        private void button3_Click(object sender, EventArgs e)
        {
            //读取,跳到多少个字节后读取
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog()==DialogResult.OK)
            {
                string fileName = ofd.FileName;
                //读取fileName对应的文件10个字节后的内容
                FileStream fs = new FileStream(fileName, FileMode.Open);
                    //将流的第10(索引号10)个位置指定为流的开始;
                fs.Seek(10, SeekOrigin.Begin);
                int i=fs.ReadByte();//读取一个字节
                MessageBox.Show(i.ToString());
                fs.Close();
            }
        }
    }

}


设计界面:


原创粉丝点击