I'm trying to copy an entire directory (including all files and subfolders) from one destination to another on game launch. I've looked at scripts mentioned previously here: https://answers.unity.com/questions/1157689/copy-an-entire-directory-to-another-folder-through.html
However, this doesn't seem to copy subfolders and subfolder contents - any suggestions would be really helpful!
You need to use recursion. Basically you have a method for copying a folder and the content to somewhere. If that folder contains any subfolders, run the same method for each subfolder, which will then do the same.
Example:
static void CopyFolder(string path, string target)
{
// Create target directory
Directory.CreateDirectory(target);
// Copy all files
foreach (string file in Directory.GetFiles(path))
File.Copy(file, Path.Combine(target, Path.GetFileName(file)));
// Recursively copy all subdirectories
foreach (string directory in Directory.GetDirectories(path))
CopyFolder(directory, Path.Combine(target, Path.GetFileName(directory)));
}
In that code it only goes through all the files in that folder. You can follow the same concept for all the directories and their files and their directories.... ( hint recursion ).
Here's how you get files Directory.EnumerateFiles
and directories Directory.EnumerateDirectories
.
try this
class Program
{
static void Main(string[] args)
{
string sourceDirectory = @"C:\temp\source";
string targetDirectory = @"C:\temp\destination";
Copy(sourceDirectory, targetDirectory);
Console.WriteLine("\r\nEnd of program");
Console.ReadKey();
}
public static void Copy(string sourceDirectory, string targetDirectory)
{
var diSource = new DirectoryInfo(sourceDirectory);
var diTarget = new DirectoryInfo(targetDirectory);
CopyAll(diSource, diTarget);
}
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.