Search This Blog

Saturday 16 July 2016

Copy file from one folder to another in c#

using System.IO;

Copy file from Root Folder to Sub Folder

string fileName = "test.txt";
string sourcePath = @"C:\Test Folder";
string targetPath = @"C:\Test Folder\Sub Folder";

string sourceFile = Path.Combine(sourcePath, fileName);
string destFile = Path.Combine(targetPath, fileName);

if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

File.Copy(sourceFile, destFile, true);    

Copy file from one folder to another folder

string fileName = "test.txt";
string sourcePath = @"C:\Source Folder";
string targetPath = @"C:\Destination Folder";

string sourceFile = Path.Combine(sourcePath, fileName);
string destFile = Path.Combine(targetPath, fileName);

if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

File.Copy(sourceFile, destFile, true);    

Copy file from one directories to another directories

string fileName = "test.txt";
string sourcePath = @"C:\Source Folder";
string targetPath = @"D:\Destination Folder";

string sourceFile = Path.Combine(sourcePath, fileName);
string destFile = Path.Combine(targetPath, fileName);

if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

File.Copy(sourceFile, destFile, true);    

Copy all files from Root Folder to Sub Folder

string sourcePath = @"C:\Test Folder";
string targetPath = @"C:\Test Folder\Sub Folder";

if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

string[] sourcefiles = Directory.GetFiles(sourcePath);

foreach (string sourcefile in sourcefiles)
{
    string fileName = Path.GetFileName(sourcefile);
    string destFile = Path.Combine(targetPath, fileName);

    File.Copy(sourcefile, destFile, true);
}

Copy all files from one folder to another folder

string sourcePath = @"C:\Source Folder";
string targetPath = @"C:\Destination Folder";

if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

string[] sourcefiles = Directory.GetFiles(sourcePath);

foreach (string sourcefile in sourcefiles)
{
    string fileName = Path.GetFileName(sourcefile);
    string destFile = Path.Combine(targetPath, fileName);

    File.Copy(sourcefile, destFile, true);
}

Copy all files from one directories to another directories

string sourcePath = @"C:\Source Folder";
string targetPath = @"D:\Destination Folder";

if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

string[] sourcefiles = Directory.GetFiles(sourcePath);

foreach (string sourcefile in sourcefiles)
{
    string fileName = Path.GetFileName(sourcefile);
    string destFile = Path.Combine(targetPath, fileName);

    File.Copy(sourcefile, destFile, true);
}

Note:-

File.Copy() third parameter is Boolean. By default it’s false. Its true means overwrite the file, if same file exists in destination folder.

No comments:

Post a Comment