Monday, 4 June 2012

Copy all files from source directroy to target directory in C#

private void CopyDirectoryFiles(string sourcePath, string targetPath)
    {
        string SrcFileName = string.Empty;
        string DestFile = string.Empty;

        if (Directory.Exists(sourcePath))
        {
            string[] Files = Directory.GetFiles(sourcePath);

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

            // Copy the files and overwrite destination files if they already exist.
            foreach (string CurrentFile in Files)
            {
                // Use static Path methods to extract only the file name from the path.
                SrcFileName = Path.GetFileName(CurrentFile);
                DestFile = Path.Combine(targetPath, SrcFileName);
                File.Copy(CurrentFile, DestFile, true);
            }
        }
    }

No comments:

Post a Comment