Windows Forms: Copy file to another directory in C#

This post shows you How to copy file to another directory in C# Windows Forms Application.

In C#, you can copy a file to another directory using the File.Copy method from the System.IO namespace.

How to copy file to another directory in C#

Here's a basic example of how to do this

Drag and Drop the TextBox, Label and button from your Visual Studio toolbox to your winform, then design a simple UI that allows you to copy file from another folder in c# as shown below.

copy file to another directory c#

Add code to handle the Browse button click event allows you to select the file you want to copy.

// c# get the file name from the source path
private void btnBrowse_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "All|*.*" })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
            txtFileName.Text = ofd.FileName;
    }
}

Add code the handle the Copy button click event allows you to copy the file to another directory.

// c# copy file.copy directory
private void btnCopy_Click(object sender, EventArgs e)
{
    // directory c# copy file
    using (FolderBrowserDialog ofd = new FolderBrowserDialog())
    {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            FileInfo fileInfo = new FileInfo(txtFileName.Text);
            // c# construct the destination path
            txtTargetPath.Text = Path.Combine(ofd.SelectedPath, fileInfo.Name);
            // c# copy the file
            File.Copy(txtFileName.Text, txtTargetPath.Text, true);
            MessageBox.Show("You have been succesfully copied.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

Press F5 to run your application, then select the file and target directory to copy.

Make sure you handle exceptions properly, especially if you're dealing with file operations, as there could be various errors that might occur during the copying process.