How to Copy file to another directory in C#

By FoxLearn 7/16/2024 9:21:33 AM   10.25K
To copy a file to another directory in a C# Windows Forms application, you can use the System.IO.File class, which provides a convenient method called Copy.

How to copy file to another directory in C#

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

Create a new Windows Forms application project, then drag and drop the TextBox, Label and button controls 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.