1. 程式人生 > >C# winForm 定時拷貝覆蓋檔案小工具

C# winForm 定時拷貝覆蓋檔案小工具

程式碼大多來源於網路

IDE:vs2017

專案檔案:

連結:https://pan.baidu.com/s/1DBUwVw3Blv2vsIBhEmTq6Q
提取碼:qmok

介面:

程式碼:

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; } } } }