C# file copy tool

Table of contents

Tool introduction

Tools background

4 files introduction

CopyTheSpecifiedSuffixFiles.exe.config

DataSave.txt

How to store copies

Introduction to folders

source folder

target folder

result

Use *.mp4

use*.*

Insist on copying when the name is the same

Possible errors

The C# code is as follows

Form1.cs

Form1.cs design

APP.config

Program.cs

Form1.Designer.cs


Tool introduction


Tools background

Do you know why I suddenly wrote this today?

I downloaded the videos yesterday and found that they are all stored in separate folders. It is too troublesome to open them one by one. I wrote this today hahaha. Take them all out and add them all to the playlist at once!

Only copy the specified file suffix to the new folder. No matter how many subfolders there are in your original folder, you can copy the files you need (but the subfolders will not be copied, that is, the original folder will not be copied . Storage structure, I did this deliberately)!

He will remember the four options you selected last time, and the next time you open them, it will be the last location.


4 files introduction


CopyTheSpecifiedSuffixFiles.exe.config

I believe you can tell what this is for at a glance, that’s right! This is the default configuration of this software, of course you can also change it in DataSave.txt.


DataSave.txt

It doesn’t exist at the beginning, but it will be automatically generated later~


How to store copies

1. Keep the original file (keep the file with the same name in the target folder)

2. Replace files (replace files with the same name in the target folder)

3. Keep and automatically add the file name (when copying, _1 will be added at the end to distinguish it, as shown below)

Only copy the specified file suffix to the new folder. No matter how many subfolders there are in your original folder, you can copy the files you need (but the subfolders will not be copied, that is, the original folder will not be copied. Storage structure, I did this deliberately)! (Say important things twice! Why not say them three times? Hahaha because there is no reason 0.o)


Introduction to folders


source folder


target folder


result


Use *.mp4


use*.*


Insist on copying when the name is the same


Possible errors

https://static.dingtalk.com/media/lQLPJwXpP0_CCKDM-80B8LDvicO4vGzluQTtO_QiALoA_496_251.png

Because you are missing this thing, just download it, a low-level gadget


The C# code is as follows

If you don’t want to do it bit by bit, you can directly download the uploaded resources.


Form1.cs

using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace CopyTheSpecifiedSuffixFiles
{
    public partial class frmCopyFiles : Form
    {
        public frmCopyFiles()
        {
            InitializeComponent();
        }

        private Stopwatch stopwatch = new Stopwatch();

        public void btnCopy_Click(object sender, EventArgs e)
        {
            // 创建 Stopwatch 对象
            stopwatch = new Stopwatch();

            // 开始计时
            stopwatch.Start();
            lblResDesc.ForeColor = System.Drawing.Color.Red;
            lblResDesc.Text = "正在拷贝,请稍等...";
            this.Refresh();

            string sourceFolderPath = txtSourceFolderPath.Text;
            string destinationFolderPath = txtDestinationFolderPath.Text;

            // 检查文件夹是否存在,不存在直接创建空的文件夹
            if (!Directory.Exists(sourceFolderPath)) Directory.CreateDirectory(sourceFolderPath);

            if (!Directory.Exists(destinationFolderPath)) Directory.CreateDirectory(destinationFolderPath);

            // 编辑txt文件并写入两个字符串
            string filePath = "DataSave.txt";

            // 写入文件
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.WriteLine(sourceFolderPath);
                writer.WriteLine(destinationFolderPath);
                writer.WriteLine(cboSuffixSelect.Text);
                writer.WriteLine(txtSuffixInfo.Text);
                writer.Flush(); // 刷新缓冲区,确保数据被写入文件
            }

            // 拷贝目标文件夹内部所有的.mp4文件至新文件夹中
            CopyFiles(sourceFolderPath, destinationFolderPath);
            lblResDesc.ForeColor = System.Drawing.Color.Green;
            lblResDesc.Text = "文件拷贝完成!";
            // 停止计时
            stopwatch.Stop();

            // 获取耗时
            TimeSpan elapsedTime = stopwatch.Elapsed;

            MessageBox.Show("文件拷贝完成!\n" + "程序执行耗时: " + Math.Round(elapsedTime.TotalMilliseconds / 1000, 1) + " 秒");
        }

        // 递归拷贝目标文件夹及其子文件夹中的所有.mp4文件至新文件夹中
        public void CopyFiles(string sourceFolderPath, string destinationFolderPath)
        {
            int fileCount = 1; // 记录已存在的文件数量

            // 获取文件列表
            string[] files = Directory.GetFiles(sourceFolderPath, txtSuffixInfo.Text);

            foreach (string file in files)
            {
                string fileName = Path.GetFileName(file);
                string destinationFilePath = Path.Combine(destinationFolderPath, fileName);

                if (File.Exists(destinationFilePath))
                {
                    string input = cboSuffixSelect.Text;
                    if (input == "1. 保留原文件")
                    {

                        continue; // 保留原文件,跳过拷贝
                    }
                    else if (input == "2. 替换文件")
                    {

                        File.Copy(file, destinationFilePath, true); // 替换文件
                    }
                    else if (input == "3. 保留并自动增加文件名称")
                    {
                        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
                        string fileExtension = Path.GetExtension(fileName);
                        string newFileName = $"{fileNameWithoutExtension}_{fileCount}{fileExtension}";
                        fileCount++;

                        destinationFilePath = Path.Combine(destinationFolderPath, newFileName);

                        try
                        {
                            File.Copy(file, destinationFilePath); // 拷贝文件
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message);
                        }
                    }
                    else
                    {
                        MessageBox.Show("请输入正确的选项!");
                        Application.Exit();
                    }
                }
                else
                {
                    File.Copy(file, destinationFilePath); // 拷贝文件
                }
            }

            string[] subDirectories = Directory.GetDirectories(sourceFolderPath);
            foreach (string subDirectory in subDirectories)
            {
                CopyFiles(subDirectory, destinationFolderPath);
            }
        }

        public void Form1_Load(object sender, EventArgs e)
        {
            // 添加选项到 ComboBox
            cboSuffixSelect.Items.Add("1. 保留原文件");
            cboSuffixSelect.Items.Add("2. 替换文件");
            cboSuffixSelect.Items.Add("3. 保留并自动增加文件名称");

            // 设置默认选中项
            cboSuffixSelect.SelectedIndex = 2;

            // 创建一个txt文件并写入两个字符串
            string filePath = "DataSave.txt";

            // 检查文件是否存在
            if (!File.Exists(filePath))
            {
                // 创建文件并写入初始内容
                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    writer.WriteLine(ConfigurationManager.AppSettings["SourceFolderPath"]);
                    writer.WriteLine(ConfigurationManager.AppSettings["DestinationFolderPath"]);
                    writer.WriteLine(ConfigurationManager.AppSettings["CopyStytle"]);
                    writer.WriteLine(ConfigurationManager.AppSettings["SuffixType"]);
                }
            }

            // 读取文件并输出每行内容
            using (StreamReader reader = new StreamReader(filePath))
            {
                txtSourceFolderPath.Text = reader.ReadLine(); // 读取第一行内容
                txtDestinationFolderPath.Text = reader.ReadLine(); // 读取第二行内容
                cboSuffixSelect.Text = reader.ReadLine();
                txtSuffixInfo.Text = reader.ReadLine();
            }
        }

        public void btnChooseSourcePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            // 设置对话框的描述文本
            folderBrowserDialog.Description = "选择文件夹";

            // 显示对话框并获取用户选择的路径
            DialogResult result = folderBrowserDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                string selectedFolderPath = folderBrowserDialog.SelectedPath;
                txtSourceFolderPath.Text = selectedFolderPath;
            }
        }

        public void btnChooseTargetPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.Description = "选择文件夹";
            DialogResult result = folderBrowserDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                string selectedFolderPath = folderBrowserDialog.SelectedPath;
                txtDestinationFolderPath.Text = selectedFolderPath;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

Form1.cs design


APP.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<appSettings>
		<!--源文件夹-->
		<add key="SourceFolderPath" value="D:\Code_VS2019\测试文件夹"/>
		<!--目标文件夹-->
		<add key="DestinationFolderPath" value="C:\Users\xxxxx\Desktop\拷贝结果"/>
		<!--复制方式-->
		<add key="CopyStytle" value="3. 保留并自动增加文件名称"/>
		<!--后缀格式-->
		<add key="SuffixType" value="*.mp4"/>
	</appSettings>
	<startup>
		<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
	</startup>
</configuration>

Program.cs

using System;
using System.Windows.Forms;

namespace CopyTheSpecifiedSuffixFiles
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmCopyFiles());
        }
    }
}

Form1.Designer.cs


namespace CopyTheSpecifiedSuffixFiles
{
    partial class frmCopyFiles
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.btnCopy = new System.Windows.Forms.Button();
            this.cboSuffixSelect = new System.Windows.Forms.ComboBox();
            this.txtSourceFolderPath = new System.Windows.Forms.TextBox();
            this.txtDestinationFolderPath = new System.Windows.Forms.TextBox();
            this.lblSourceDesc = new System.Windows.Forms.Label();
            this.lblTargetDesc = new System.Windows.Forms.Label();
            this.btnChooseSourcePath = new System.Windows.Forms.Button();
            this.btnChooseTargetPath = new System.Windows.Forms.Button();
            this.lblSaveSelectDesc = new System.Windows.Forms.Label();
            this.lblSuffixSelectDesc = new System.Windows.Forms.Label();
            this.txtSuffixInfo = new System.Windows.Forms.TextBox();
            this.lblSuffixInfoDesc = new System.Windows.Forms.Label();
            this.lblResDesc = new System.Windows.Forms.Label();
            this.btnClose = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // btnCopy
            // 
            this.btnCopy.AutoSize = true;
            this.btnCopy.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.btnCopy.Location = new System.Drawing.Point(494, 52);
            this.btnCopy.Name = "btnCopy";
            this.btnCopy.Size = new System.Drawing.Size(107, 52);
            this.btnCopy.TabIndex = 0;
            this.btnCopy.Text = "拷贝";
            this.btnCopy.UseVisualStyleBackColor = true;
            this.btnCopy.Click += new System.EventHandler(this.btnCopy_Click);
            // 
            // cboSuffixSelect
            // 
            this.cboSuffixSelect.Font = new System.Drawing.Font("宋体", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.cboSuffixSelect.FormattingEnabled = true;
            this.cboSuffixSelect.Location = new System.Drawing.Point(107, 148);
            this.cboSuffixSelect.Name = "cboSuffixSelect";
            this.cboSuffixSelect.Size = new System.Drawing.Size(198, 22);
            this.cboSuffixSelect.TabIndex = 1;
            // 
            // txtSourceFolderPath
            // 
            this.txtSourceFolderPath.Location = new System.Drawing.Point(107, 40);
            this.txtSourceFolderPath.Name = "txtSourceFolderPath";
            this.txtSourceFolderPath.Size = new System.Drawing.Size(302, 21);
            this.txtSourceFolderPath.TabIndex = 2;
            // 
            // txtDestinationFolderPath
            // 
            this.txtDestinationFolderPath.Location = new System.Drawing.Point(107, 94);
            this.txtDestinationFolderPath.Name = "txtDestinationFolderPath";
            this.txtDestinationFolderPath.Size = new System.Drawing.Size(300, 21);
            this.txtDestinationFolderPath.TabIndex = 3;
            // 
            // lblSourceDesc
            // 
            this.lblSourceDesc.AutoSize = true;
            this.lblSourceDesc.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.lblSourceDesc.Location = new System.Drawing.Point(27, 42);
            this.lblSourceDesc.Name = "lblSourceDesc";
            this.lblSourceDesc.Size = new System.Drawing.Size(76, 16);
            this.lblSourceDesc.TabIndex = 4;
            this.lblSourceDesc.Text = "源文件夹";
            // 
            // lblTargetDesc
            // 
            this.lblTargetDesc.AutoSize = true;
            this.lblTargetDesc.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.lblTargetDesc.Location = new System.Drawing.Point(12, 96);
            this.lblTargetDesc.Name = "lblTargetDesc";
            this.lblTargetDesc.Size = new System.Drawing.Size(93, 16);
            this.lblTargetDesc.TabIndex = 5;
            this.lblTargetDesc.Text = "目标文件夹";
            // 
            // btnChooseSourcePath
            // 
            this.btnChooseSourcePath.AutoSize = true;
            this.btnChooseSourcePath.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.btnChooseSourcePath.Location = new System.Drawing.Point(415, 37);
            this.btnChooseSourcePath.Name = "btnChooseSourcePath";
            this.btnChooseSourcePath.Size = new System.Drawing.Size(52, 26);
            this.btnChooseSourcePath.TabIndex = 6;
            this.btnChooseSourcePath.Text = "选择";
            this.btnChooseSourcePath.UseVisualStyleBackColor = true;
            this.btnChooseSourcePath.Click += new System.EventHandler(this.btnChooseSourcePath_Click);
            // 
            // btnChooseTargetPath
            // 
            this.btnChooseTargetPath.AutoSize = true;
            this.btnChooseTargetPath.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.btnChooseTargetPath.Location = new System.Drawing.Point(415, 91);
            this.btnChooseTargetPath.Name = "btnChooseTargetPath";
            this.btnChooseTargetPath.Size = new System.Drawing.Size(52, 26);
            this.btnChooseTargetPath.TabIndex = 7;
            this.btnChooseTargetPath.Text = "选择";
            this.btnChooseTargetPath.UseVisualStyleBackColor = true;
            this.btnChooseTargetPath.Click += new System.EventHandler(this.btnChooseTargetPath_Click);
            // 
            // lblSaveSelectDesc
            // 
            this.lblSaveSelectDesc.AutoSize = true;
            this.lblSaveSelectDesc.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.lblSaveSelectDesc.Location = new System.Drawing.Point(27, 151);
            this.lblSaveSelectDesc.Name = "lblSaveSelectDesc";
            this.lblSaveSelectDesc.Size = new System.Drawing.Size(76, 16);
            this.lblSaveSelectDesc.TabIndex = 8;
            this.lblSaveSelectDesc.Text = "存储方式";
            // 
            // lblSuffixSelectDesc
            // 
            this.lblSuffixSelectDesc.AutoSize = true;
            this.lblSuffixSelectDesc.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.lblSuffixSelectDesc.Location = new System.Drawing.Point(27, 205);
            this.lblSuffixSelectDesc.Name = "lblSuffixSelectDesc";
            this.lblSuffixSelectDesc.Size = new System.Drawing.Size(76, 16);
            this.lblSuffixSelectDesc.TabIndex = 9;
            this.lblSuffixSelectDesc.Text = "填入后缀";
            // 
            // txtSuffixInfo
            // 
            this.txtSuffixInfo.Location = new System.Drawing.Point(107, 203);
            this.txtSuffixInfo.Name = "txtSuffixInfo";
            this.txtSuffixInfo.Size = new System.Drawing.Size(131, 21);
            this.txtSuffixInfo.TabIndex = 10;
            // 
            // lblSuffixInfoDesc
            // 
            this.lblSuffixInfoDesc.AutoSize = true;
            this.lblSuffixInfoDesc.Font = new System.Drawing.Font("宋体", 10.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.lblSuffixInfoDesc.ForeColor = System.Drawing.Color.DodgerBlue;
            this.lblSuffixInfoDesc.Location = new System.Drawing.Point(270, 206);
            this.lblSuffixInfoDesc.Name = "lblSuffixInfoDesc";
            this.lblSuffixInfoDesc.Size = new System.Drawing.Size(122, 14);
            this.lblSuffixInfoDesc.TabIndex = 11;
            this.lblSuffixInfoDesc.Text = "填入格式:*.mp4";
            // 
            // lblResDesc
            // 
            this.lblResDesc.AutoSize = true;
            this.lblResDesc.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.lblResDesc.ForeColor = System.Drawing.Color.Green;
            this.lblResDesc.Location = new System.Drawing.Point(338, 151);
            this.lblResDesc.Name = "lblResDesc";
            this.lblResDesc.Size = new System.Drawing.Size(263, 16);
            this.lblResDesc.TabIndex = 12;
            this.lblResDesc.Text = "请选择相应参数并点击拷贝按钮!";
            // 
            // btnClose
            // 
            this.btnClose.AutoSize = true;
            this.btnClose.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.btnClose.Location = new System.Drawing.Point(494, 184);
            this.btnClose.Name = "btnClose";
            this.btnClose.Size = new System.Drawing.Size(107, 52);
            this.btnClose.TabIndex = 13;
            this.btnClose.Text = "关闭";
            this.btnClose.UseVisualStyleBackColor = true;
            this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
            // 
            // frmCopyFiles
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(614, 258);
            this.Controls.Add(this.btnClose);
            this.Controls.Add(this.lblResDesc);
            this.Controls.Add(this.lblSuffixInfoDesc);
            this.Controls.Add(this.txtSuffixInfo);
            this.Controls.Add(this.lblSuffixSelectDesc);
            this.Controls.Add(this.lblSaveSelectDesc);
            this.Controls.Add(this.btnChooseTargetPath);
            this.Controls.Add(this.btnChooseSourcePath);
            this.Controls.Add(this.lblTargetDesc);
            this.Controls.Add(this.lblSourceDesc);
            this.Controls.Add(this.txtDestinationFolderPath);
            this.Controls.Add(this.txtSourceFolderPath);
            this.Controls.Add(this.cboSuffixSelect);
            this.Controls.Add(this.btnCopy);
            this.Name = "frmCopyFiles";
            this.Text = "文件拷贝工具";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnCopy;
        private System.Windows.Forms.ComboBox cboSuffixSelect;
        private System.Windows.Forms.TextBox txtSourceFolderPath;
        private System.Windows.Forms.TextBox txtDestinationFolderPath;
        private System.Windows.Forms.Label lblSourceDesc;
        private System.Windows.Forms.Label lblTargetDesc;
        private System.Windows.Forms.Button btnChooseSourcePath;
        private System.Windows.Forms.Button btnChooseTargetPath;
        private System.Windows.Forms.Label lblSaveSelectDesc;
        private System.Windows.Forms.Label lblSuffixSelectDesc;
        private System.Windows.Forms.TextBox txtSuffixInfo;
        private System.Windows.Forms.Label lblSuffixInfoDesc;
        private System.Windows.Forms.Label lblResDesc;
        private System.Windows.Forms.Button btnClose;
    }
}

Guess you like

Origin blog.csdn.net/qq_57163366/article/details/132740182