复制功能代码

时间:2022-05-19 23:04:13 阅读: 最新文章 文档下载
说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。
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 FileCopy {

public partial class Frm_Main : Form {

public Frm_Main() {

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e) {

openFileDialog1.FileName = "";

if (openFileDialog1.ShowDialog() == DialogResult.OK) textBox1.Text = openFileDialog1.FileName; }

private void button2_Click(object sender, EventArgs e) {

folderBrowserDialog1.SelectedPath = "";

if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) textBox2.Text = folderBrowserDialog1.SelectedPath; }

private void button3_Click(object sender, EventArgs e) {

if (textBox1.Text.Length == 0 || textBox2.Text.Length == 0) MessageBox.Show("请选择原文件路径或目的文件路径。"); else

{

string tem_Dfile = textBox1.Text;

tem_Dfile = tem_Dfile.Substring(tem_Dfile.LastIndexOf("\\") + 1, tem_Dfile.Length - tem_Dfile.LastIndexOf("\\") - 1);

tem_Dfile = textBox2.Text + "\\" + tem_Dfile; CopyFile(textBox1.Text, tem_Dfile, 1024); }

}

FileStream FormerOpen; FileStream ToFileOpen;


///

/// 文件的复制 ///


/// 源文件路径 /// 目的文件路径

/// 传输大小

/// ProgressBar控件 public void CopyFile(string FormerFile, string toFile, int SectSize) {

FileStream fileToCreate = new FileStream(toFile, FileMode.Create); //创建目的文件,如果已存在将被覆盖

fileToCreate.Close(); //关闭所有资源

fileToCreate.Dispose(); //释放所有资源

FormerOpen = new FileStream(FormerFile, FileMode.Open, FileAccess.Read);//以只读方式打开源文件

ToFileOpen = new FileStream(toFile, FileMode.Append, FileAccess.Write); //以写方式打开目的文件

//根据一次传输的大小,计算传输的个数 int FileSize; //要拷贝的文件的大小

//如果分段拷贝,即每次拷贝内容小于文件总长度 if (SectSize < FormerOpen.Length)

{

byte[] buffer = new byte[SectSize]; //根据传输的大小,定义一个字节数组 int copied = 0; //记录传输的大小

while (copied <= ((int)FormerOpen.Length - SectSize)) //拷贝主体部分

{

FileSize = FormerOpen.Read(buffer, 0, SectSize); //0开始读,每次最大读SectSize FormerOpen.Flush(); //清空缓存

ToFileOpen.Write(buffer, 0, SectSize); //向目的文件写入字节 ToFileOpen.Flush(); //清空缓存

ToFileOpen.Position = FormerOpen.Position; //使源文件和目的文件流的位置相同 copied += FileSize; //记录已拷贝的大小

}

int left = (int)FormerOpen.Length - copied; //获取剩余大小 FileSize = FormerOpen.Read(buffer, 0, left); //读取剩余的字节 FormerOpen.Flush(); //清空缓存

ToFileOpen.Write(buffer, 0, left); //写入剩余的部分 ToFileOpen.Flush(); //清空缓存 }

//如果整体拷贝,即每次拷贝内容大于文件总长度 else

{

byte[] buffer = new byte[FormerOpen.Length]; //获取文件的大小

FormerOpen.Read(buffer, 0, (int)FormerOpen.Length); //读取源文件的字节


FormerOpen.Flush(); //清空缓存

ToFileOpen.Write(buffer, 0, (int)FormerOpen.Length); //写放字节 ToFileOpen.Flush(); //清空缓存 }

FormerOpen.Close(); //释放所有资源 ToFileOpen.Close(); //释放所有资源 MessageBox.Show("文件复制完成"); } } }


本文来源:https://www.wddqw.com/doc/ca199e262f60ddccda38a04b.html