Wednesday, June 17, 2026

C# Copy file into target folder - FileInfo CopyTo method

Example Copy files in a target folder

string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string source_folder = Path.Combine(desktop, "source_folder");
string target_file = "cookies.txt";

if (Directory.Exists(source_folder))
{
    FileInfo fileInfo = new FileInfo(Path.Combine(source_folder, target_file));
    // Check if the file exists before trying to access its properties
    if (fileInfo.Exists)
    {
        // copy the file to the desktop, overwriting if it already exists
        fileInfo.CopyTo(Path.Combine(desktop, target_file), true);
        Console.WriteLine($"The file {target_file} is copied successfully.");
    }
    else
    {
        Console.WriteLine($"The file {target_file} does not exist in the source folder.");
    }
}

No comments:

Post a Comment

Hot Topics