How to Copy file to another directory in C#
By FoxLearn 11/23/2024 4:31:10 AM 10.6K
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.
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.
// copy file c# 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 file to directory 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.