📜  如何在文件资源管理器中将文件添加到新文件 (1)

📅  最后修改于: 2023-12-03 14:52:56.210000             🧑  作者: Mango

如何在文件资源管理器中将文件添加到新文件

这里介绍一种在Windows系统的文件资源管理器中将文件添加到新文件的方法,使用C#语言实现。

1.准备工作

首先需要在Visual Studio中创建一个Windows Form应用程序,并添加引用System.Runtime.InteropServicesSystem.Windows.Forms

然后,在Main函数中添加以下代码:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}
2.实现添加文件到新文件的功能

接下来,我们在Form1窗口中添加一个按钮和一个TextBox控件,用于选择要添加到新文件的文件路径。在按钮的Click事件中添加以下代码:

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Multiselect = false;

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string filePath = openFileDialog1.FileName;
        textBox1.Text = filePath;

        DirectoryInfo directoryInfo = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\New Folder");
        if (!directoryInfo.Exists)
        {
            directoryInfo.Create();
        }

        File.Copy(filePath, directoryInfo.FullName + "\\" + Path.GetFileName(filePath));

        MessageBox.Show("文件已添加");
    }
}

第一行代码创建了一个OpenFileDialog对象,用于选择要添加到新文件的文件。

然后判断用户是否选择了文件,如果选择了文件,则获取文件路径并将文件路径显示在TextBox控件中。

接下来创建一个名为“New Folder”的文件夹,用于存储添加到新文件的文件。如果该文件夹不存在,则创建该文件夹。

然后使用File类的Copy方法将文件复制到新文件夹中,并使用Path类的GetFileName方法获取文件名。

最后显示一个消息框,提示用户文件已添加到新文件。

3.完整代码
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Multiselect = false;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog1.FileName;
                textBox1.Text = filePath;

                DirectoryInfo directoryInfo = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\New Folder");
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }

                File.Copy(filePath, directoryInfo.FullName + "\\" + Path.GetFileName(filePath));

                MessageBox.Show("文件已添加");
            }
        }
    }
}
4.运行效果