C# winForm 定時拷貝覆蓋文件小工具


代碼大多來源於網絡

IDE:vs2017

項目文件:

鏈接: https://pan.baidu.com/s/1zA3dMoSHDdggInzOP8kKuw

提取碼: ipgr

界面:

代碼:

using System;
using System.Net;
using System.Windows.Forms;
using System.IO;

namespace CopyAndCoverFiles
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //窗體載入時執行
        private void Form1_Load(object sender, EventArgs e)
        {

            //顯示當前時間
            Text = "北京時間(本地):" + DateTime.Now.ToString("yyyy年MM月dd dddd HH時mm分");

            //啟動顯示時間的計時器
            TimerShowTime.Start();
            TimerShowTime.Interval = 60000;

            //設置倒計時定時器間隔
            TimerLastTime.Interval = 1000;//間隔1秒
        }

        //標題欄循環顯示時間
        private void TimerShowTime_Tick(object sender, EventArgs e)
        {
            ShowTime();
        }

        //標題欄顯示時間
        private void ShowTime()
        {

            if (GetNetDateTime() != "")
            {
                Text = "北京時間(網絡):" + Convert.ToDateTime(GetNetDateTime()).ToString("yyyy年MM月dd dddd HH時mm分");
            }

            else
            {
                Text = "北京時間(本地):" + DateTime.Now.ToString("yyyy年MM月dd dddd HH時mm分");
            }

        }

        //獲取網絡時間
        private static string GetNetDateTime()
        {

            WebRequest request = null;
            WebResponse response = null;
            WebHeaderCollection headerCollection = null;
            string datetime = string.Empty;

            try
            {
                request = WebRequest.Create("https://www.baidu.com");
                request.Timeout = 3000;
                request.Credentials = CredentialCache.DefaultCredentials;
                response = request.GetResponse();
                headerCollection = response.Headers;

                foreach (var h in headerCollection.AllKeys)
                {

                    if (h == "Date")
                    {
                        datetime = headerCollection[h];
                    }

                }

                return datetime;
            }

            catch (Exception) { return datetime; }

            finally
            {
                if (request != null)
                { request.Abort(); }

                if (response != null)
                { response.Close(); }

                if (headerCollection != null)
                { headerCollection.Clear(); }
            }
        }
        //選擇目標文件夾按鈕
        private void BtnSeleteTargetFolder_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                TxbTargetFolder.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        //選擇源文件夾按鈕
        private void BtnSeleteSourceFolder_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                TxbSourceFolder.Text = folderBrowserDialog1.SelectedPath;
            }

        }

        //輸入源文件夾后遍歷顯示文件
        private void TxbSourceFolder_TextChanged(object sender, EventArgs e)
        {

            if (TxbSourceFolder.Text.Trim() != "")
            {
                //初始化文件列表
                CheckedListBoxFiles.Items.Clear();

                //如果文件夾存在
                if (Directory.Exists(TxbSourceFolder.Text.Trim()))
                {
                    try
                    {
                        DirectoryInfo sourceFolder = new DirectoryInfo(TxbSourceFolder.Text);

                        //遍歷顯示文件
                        foreach (FileInfo nextFile in sourceFolder.GetFiles())
                        {

                            CheckedListBoxFiles.Items.Add(nextFile.Name);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("獲取源文件內文件列表失敗:" + ex.Message);
                    }
                }
            }
        }

        //執行按鈕
        private void BtnCountdown_Click(object sender, EventArgs e)
        {
            if (Checking())
            {
                //彈出警告窗口
                DialogResult warning = MessageBox.Show("目標文件夾內的同名文件將被覆蓋,執行前請備份好目標文件夾,繼續嗎?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

                if (warning == DialogResult.OK)
                {
                    Start();//開始執行
                }
            }

        }

        //暫停按鈕
        private void BtnPause_Click(object sender, EventArgs e)
        {
            Pause();//暫停執行

            //修改設置的同步次數
            if (toolStripStatusLabel3.Text != "無限")
            {
                NumTxbLoopCount.Value = Convert.ToDecimal(toolStripStatusLabel3.Text);
            }
            else
            {
                NumTxbLoopCount.Value = 0;
            }
        }

        //倒數定時器
        private void TimerCountdown_Tick(object sender, EventArgs e)
        {
            //暫停倒計時計時器
            TimerLastTime.Stop();

            //更新顯示倒數次數
            if (toolStripStatusLabel3.Text != "無限")
            {
                int loopCount = Convert.ToInt32(toolStripStatusLabel3.Text);

                if (loopCount > 0)
                {
                    loopCount--;
                    //啟動倒計時計時器
                    TimerLastTime.Start();

                    if (loopCount == 0)
                    {
                        Pause();
                    }
                }

                toolStripStatusLabel3.Text = loopCount + "";
            }
            else
            {
                //啟動倒計時計時器
                TimerLastTime.Start();
            }

            //初始化倒計時顯示
            toolStripStatusLabel4.Text = SecondToTime(TimerCountdown.Interval / 1000);

            //復制且覆蓋文件
            CopyAndCoverFile();
        }

        //復制且覆蓋文件
        private void CopyAndCoverFile()
        {
            if (Checking())
            {
                string targetFolderPath = TxbTargetFolder.Text + @"\";//目標文件夾路徑
                string sourceFolderPath = TxbSourceFolder.Text + @"\";//源文件夾路徑

                //遍歷復制選中的文件
                for (int i = 0; i < CheckedListBoxFiles.CheckedItems.Count; i++)
                {
                    string fileName = CheckedListBoxFiles.GetItemText(CheckedListBoxFiles.CheckedItems[i]);//取得文件名
                    try
                    {
                        File.Copy(sourceFolderPath + fileName, targetFolderPath + fileName, true);//復制覆蓋同名文件
                    }
                    catch (Exception ex)
                    {
                        Pause();//暫停執行
                        MessageBox.Show("執行失敗:" + ex.Message);
                    }
                }
            }
        }

        //倒計時定時器調用
        private void TimerLastTime_Tick(object sender, EventArgs e)
        {
            //將時:分:秒轉換為秒
            string[] str = toolStripStatusLabel4.Text.Split(new char[] { ':' });
            int lastTime = Convert.ToInt32(str[0]) * 3600 + Convert.ToInt32(str[1]) * 60 + Convert.ToInt32(str[2]);

            //更新倒計時
            if (lastTime == 1)
            {
                lastTime = TimerCountdown.Interval / 1000;
            }
            else
            {
                lastTime--;
            }

            toolStripStatusLabel4.Text = SecondToTime(lastTime);
        }

        //復制文件前檢查
        private bool Checking()
        {
            bool ok = false;
            if (TxbTargetFolder.Text.Trim() != TxbSourceFolder.Text.Trim())
            {
                //如果目標文件夾存在
                if (Directory.Exists(TxbTargetFolder.Text))
                {
                    //如果勾選的文件數大於0
                    if (CheckedListBoxFiles.CheckedItems.Count > 0)
                    {

                        if (NumTxbHour.Value == 0 && NumTxbMinute.Value == 0 && NumTxbSecond.Value == 0)
                        {
                            MessageBox.Show("倒計時不能為0");
                        }
                        else
                        {
                            ok = true;
                        }
                    }
                    else
                    {
                        MessageBox.Show("請至少勾選一個文件");
                    }
                }
                //目標文件夾不存在
                else
                {
                    Pause();//暫停執行
                    MessageBox.Show("目標文件夾不存在,請重新選擇");
                }
            }
            else
            {
                MessageBox.Show("目標文件夾和源文件夾路徑不能相同");
            }

            return ok;
        }

        //開始執行
        private void Start()
        {

            GroupBoxForm.Enabled = false;//禁用界面輸入
            BtnCountdown.Enabled = false;//禁用執行按鈕
            BtnPause.Enabled = true;//啟用暫停按鈕

            //執行間隔時間
            int countdown = 0;
            countdown += Convert.ToInt32(NumTxbHour.Value) * 3600;//小時
            countdown += Convert.ToInt32(NumTxbMinute.Value) * 60;//分鍾
            countdown += Convert.ToInt32(NumTxbSecond.Value);//秒鍾

            //初始化倒計時顯示
            toolStripStatusLabel4.Text = SecondToTime(countdown);

            //設置倒數計時器間隔
            TimerCountdown.Interval = countdown * 1000;//單位毫秒

            //啟動倒數計時器
            TimerCountdown.Start();
            //啟動倒計時定時器
            TimerLastTime.Start();

            //初始化剩余執行次數
            if (NumTxbLoopCount.Value == 0)
            {
                toolStripStatusLabel3.Text = "無限";
            }
            else
            {
                toolStripStatusLabel3.Text = NumTxbLoopCount.Value + "";
            }
        }

        //暫停執行
        private void Pause()
        {

            //停止倒數定時器
            TimerCountdown.Stop();
            //停止倒計時定時器
            TimerLastTime.Stop();

            GroupBoxForm.Enabled = true;//啟用界面輸入
            BtnCountdown.Enabled = true;//啟用執行按鈕
            BtnPause.Enabled = false;//禁用暫停按鈕
        }

        //將傳入的秒鍾轉換為 時:分:秒 的字符串
        private string SecondToTime(int countdown)
        {

            string time = "";
            string[] arrLastTime = { "0", "0", "0" };//時,分,秒
            arrLastTime[0] = countdown / 3600 + "";//得出小時

            //得出分鍾
            if ((countdown % 3600) > 0)
            {
                arrLastTime[1] = (countdown % 3600) / 60 + "";

                int second = (countdown % 3600) % 60;
                if (second > 0)
                {
                    arrLastTime[2] = second + "";
                }
            }
            time = String.Join(":", arrLastTime);

            return time;
        }

        //托盤圖標雙擊
        private void NotifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //還原窗體顯示    
                WindowState = FormWindowState.Normal;
                //激活窗體並給予它焦點
                Activate();
                //任務欄區顯示圖標
                ShowInTaskbar = true;
                //托盤區圖標隱藏
                NotifyIcon1.Visible = false;
            }
        }

        //窗口最小化時
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            //判斷是否選擇的是最小化按鈕
            if (WindowState == FormWindowState.Minimized)
            {
                //隱藏任務欄區圖標
                ShowInTaskbar = false;
                //圖標顯示在托盤區
                NotifyIcon1.Visible = true;
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM