Windows Forms: Copy file to another directory in C#

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

Drag the TextBox, Label and button from your visual 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.

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.

private void btnCopy_Click(object sender, EventArgs e)
{
    using (FolderBrowserDialog ofd = new FolderBrowserDialog())
    {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            FileInfo fileInfo = new FileInfo(txtFileName.Text);
            txtTargetPath.Text = Path.Combine(ofd.SelectedPath, fileInfo.Name);
            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.