Gentle
Gentle

Reputation: 87

Copy everything in a Directory and rename copied Files

I try to copy everything in a Folder to another, in this case from "sourceFolder" to "targetFolder".

Lets say "sourceFolder" would have two Files in it and 2 subfolder with one additional File: (i try to show it)

//sourceFolder
//├File1.txt
//├File2.txt
//├Subfolder1
//| └File3.txt
//|
//└Subfolder2
//  └File4.txt

Now I'm trying to copy all of those files and subfolders from "sourceFolder" to "targetFolder", the subfolders shall be titled the same and on the Files i would to add "a" in front of "Filex.txt"(Exaple: "aFilex.txt") Thats what im tring to get:

//targetFolder
//├aFile1.txt
//├aFile2.txt
//├Subfolder1
//| └aFile3.txt
//|
//└Subfolder2
//  └aFile4.txt

current Code:

string[] sourceDirectoryFiles = Directory.GetFiles(sourceFolderTextbox.Text);
string[] sourceDirectorysubfolders = Directory.GetDirectories(targetFolderTextbox.Text);
string sourcedirectory = sourceFolderTextbox.Text;
string targetdirectory = targetFolderTextbox.Text;

    if (Directory.Exists(sourceDirectorysubfolders[0]))
    {
        foreach (string sourceFilePath in sourceDirectorysubfolders)
        {
                if (!Directory.Exists(sourceFilePath))
                    {
                        Directory.CreateDirectory(sourceFilePath.Replace(sourcedirectory, targetdirectory));
                    }
            }
    }

    foreach (string sourceFilePath in sourceDirectoryFiles )
    {
        string newsourcefilePath = String.Empty;
        string newfilePath = String.Empty;
        string FileName = System.IO.Path.GetFileName(sourceFilePath);
        newsourcefilePath = sourcedirectory + "\\a" + FileName;

        System.IO.File.Copy(sourceFilePath, newfilePath ,true)
    }

I hope, I asked clear :) otherwise I'll answer your questions :)

I'm not good at English or programming so constructive criticism is welcome :)

Upvotes: 0

Views: 1552

Answers (1)

Baga
Baga

Reputation: 1452

Have modified the solution in this SO Question to suit your needs. Hope it helps.

void Copy(string sourcePath, string targetPath)
{

    foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
        Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));

    string newPath;
    foreach (string srcPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
    {
        newPath = srcPath.Replace(sourcePath, targetPath);
        newPath = newPath.Insert(newPath.LastIndexOf("\\") + 1, "a"); //prefixing 'a'
        newPath = newPath +  ".example";
        File.Copy(srcPath, newPath, true);
    }
}

Upvotes: 2

Related Questions