C#通過FileStream復(fù)制文件

界面.jpg
運(yùn)行.jpg
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 CopyFileExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void SelectButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "請(qǐng)選擇要復(fù)制的文件";
            ofd.InitialDirectory = @"C:\Users\Sudo\桌面";
            ofd.Filter = "所有文件|*.*";
            ofd.ShowDialog();
            SourceFileTextBox.Text = ofd.FileName;
            
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "請(qǐng)選擇要保存文件路徑";
            sfd.InitialDirectory = @"C:\Users\Sudo\桌面";
            sfd.Filter = "所有文件|*.*";
            sfd.ShowDialog();
            DestFileTextBox.Text = sfd.FileName;
            //先讀取  再寫入
            using (FileStream fsRead = new FileStream(SourceFileTextBox.Text.Trim(), FileMode.OpenOrCreate, FileAccess.Read))
            {
                using(FileStream fsWrite = new FileStream(DestFileTextBox.Text.Trim(), FileMode.OpenOrCreate, FileAccess.Write))
                {
                    //設(shè)置進(jìn)度條最大值
                    SaveFileProgressBar.Maximum = (int)fsRead.Length;
                    //設(shè)置緩沖區(qū)大小
                    byte[] buffer = new byte[1024 * 1024 * 3];
                    while (true)
                    {
                        //讀
                        int r = fsRead.Read(buffer, 0, buffer.Length);
                        if (r==0)
                        {
                            break;
                        }
                        //寫
                        fsWrite.Write(buffer, 0, r);
                        //進(jìn)度條進(jìn)度值與寫入數(shù)據(jù)大小關(guān)聯(lián)
                        SaveFileProgressBar.Value =(int)fsWrite.Length;
                    }
                    MessageBox.Show("保存成功!");
                }
            }
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容