复制目录中的所有内容并重命名复制的文件

时间:2014-08-01 09:25:00

标签: c# directory subdirectory

我尝试将文件夹中的所有内容复制到另一个文件夹,在这种情况下,从“sourceFolder”复制到“targetFolder”。

让我们说“sourceFolder”里面有两个文件,另外两个子文件夹有一个额外的文件: (我试着表明)

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

现在我正在尝试将所有这些文件和子文件夹从“sourceFolder”复制到“targetFolder”,子文件夹的标题应相同,在文件上我将在“Filex.txt”前添加“a” “(Exaple:”aFilex.txt“) 这是什么意思得到:

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

当前代码:

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)
    }

我希望,我问清楚:) 否则我会回答你的问题:)

我不擅长英语或编程,所以欢迎建设性的批评:)

1 个答案:

答案 0 :(得分:1)

已修改此SO Question中的解决方案以满足您的需求。希望它有所帮助。

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);
    }
}