将一个txt文本的内容复制到另一个txt文本中。
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 FileCopyPlan
{
public partial class Frm_Main : Form
{
public Frm_Main()
{
InitializeComponent();
}
public void CopyFile(string FormerFile, string toFile, int SectSize, ProgressBar progressBar1)
{
progressBar1.Value = 0;
progressBar1.Minimum = 0;
FileStream fileToCreate = new FileStream(toFile, FileMode.Create);
fileToCreate.Close();
fileToCreate.Dispose();
FileStream FormerOpen = new FileStream(FormerFile, FileMode.Open, FileAccess.Read);
FileStream ToFileOpen = new FileStream(toFile, FileMode.Append, FileAccess.Write);
int max = Convert.ToInt32(Math.Ceiling((double)FormerOpen.Length / (double)SectSize));
progressBar1.Maximum = max;
int FileSize;
if (SectSize < FormerOpen.Length)
{
byte[] buffer = new byte[SectSize];
int copied = 0;
int tem_n = 1;
while (copied <= ((int)FormerOpen.Length - SectSize))
{
FileSize = FormerOpen.Read(buffer, 0, SectSize);
FormerOpen.Flush();
ToFileOpen.Write(buffer, 0, SectSize);
ToFileOpen.Flush();
ToFileOpen.Position = FormerOpen.Position;
copied += FileSize;
progressBar1.Value = progressBar1.Value + tem_n;
}
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();
if (MessageBox.Show("复制完成!") == DialogResult.OK)
{
progressBar1.Value = 0;
textBox1.Clear();
textBox2.Clear();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
textBox2.Text = openFileDialog2.FileName;
}
}
private void button3_Click(object sender, EventArgs e)
{
CopyFile(textBox1.Text, textBox2.Text, 1, progressBar1);
}
}
}
运行结果: