How to copy a file in C#
By FoxLearn 6/15/2024 4:39:48 AM 293
The File.Copy
method is particularly useful for copying files. Here is a basic example of how to use it:
using System; using System.IO; class Program { static void Main() { // Define the source and destination file paths string sourceFilePath = @"C:\source\fileName.txt"; string destinationFilePath = @"C:\destination\fileName.txt"; try { // c# copy the file File.Copy(sourceFilePath, destinationFilePath); // If you want to overwrite the destination file if it already exists // File.Copy(sourceFilePath, destinationFilePath, true); } catch (Exception ex) { Console.WriteLine("An unexpected error occurred: " + ex.Message); } } }
File.Copy(sourceFilePath, destinationFilePath);
copies the file from the source path to the destination path.
File.Copy(sourceFilePath, destinationFilePath, true);
overwrites the destination file if it already exists.
You can also use the FileInfo
to copy your file.
string fileName = @"C://fileName.txt"; string destinationFile = @"C://destinationFile.txt"; FileInfo fi = new FileInfo(fileName); try { // c# copy file to new location fi.CopyTo(destinationFile, true); } catch (IOException iox) { Console.WriteLine(iox.Message); }
The CopyTo
method copies an existing file to a new location. It takes two parameters: the source file name (with full path) and an optional destination file name. The optional second parameter specifies whether to overwrite an existing file at the destination. If set to true
, the CopyTo
method will overwrite the file if it already exists.