gpt4 book ai didi

c# - ASP.NET C# 使用 System.IO 复制目录和子目录

转载 作者:太空狗 更新时间:2023-10-30 00:09:10 24 4
gpt4 key购买 nike

我需要将整个目录C:\X复制到C:\Y\X,我还需要复制子文件夹。
有什么方法可以使用 System.IO.File\Directory 命名空间吗?
感谢所有帮助者!

最佳答案

此类将复制或移动文件夹,无需递归调用。
这些方法使用自己的堆栈来处理递归,这是为了避免 StackOverflowException

public static class CopyFolder
{
public static void CopyDirectory(string source, string target)
{
var stack = new Stack<Folders>();
stack.Push(new Folders(source, target));

while (stack.Count > 0)
{
var folders = stack.Pop();
Directory.CreateDirectory(folders.Target);
foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
{
string targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile);
File.Copy(file, targetFile);
}

foreach (var folder in Directory.GetDirectories(folders.Source))
{
stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
}
}
}
public static void MoveDirectory(string source, string target)
{
var stack = new Stack<Folders>();
stack.Push(new Folders(source, target));

while (stack.Count > 0)
{
var folders = stack.Pop();
Directory.CreateDirectory(folders.Target);
foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
{
string targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile);
File.Move(file, targetFile);
}

foreach (var folder in Directory.GetDirectories(folders.Source))
{
stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
}
}
Directory.Delete(source, true);
}
public class Folders
{
public string Source { get; private set; }
public string Target { get; private set; }

public Folders(string source, string target)
{
Source = source;
Target = target;
}
}
}

关于c# - ASP.NET C# 使用 System.IO 复制目录和子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2801165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com