所以我一直在构建一个可重用的类来处理递归和将目录1复制到另一个目录。文件夹结构是:
D:\Arrigotti
)C:\inetpub\wwwroot
)D:\Arrigotti\Backup
)D:\Arrigotti\Archive
)这些是关键领域,因为示例代码I为了简单起见省略了一些验证/错误处理。
public static class FileSystem
{
public static void CopyDirectory(string source, string destination)
{
DirectoryInfo directory = new DirectoryInfo(source);
DirectoryInfo[] directories = directory.GetDirectories();
foreach(DirectoryInfo dir in directories)
{
Console.WriteLine(@"Found Directory: {0}", dir.FullName);
if(Directory.Exists(Path.Combine(destination, dir.Name)))
{
Console.WriteLine(@"Attempting to write directory...");
Directory.CreateDirectory(Path.Combine(destination, dir.Name));
Console.WriteLine(@"Created Directory: {0}", dir.Name);
}
CopyDirectory(dir.FullName, Path.Combine(destination, dir.Name));
FileInfo[] files = dir.GetFiles();
foreach(FileInfo file in files)
{
Console.WriteLine(@"Found: {0}", file.FullName);
Console.WriteLine(@"Attempting to copy...");
file.CopyTo(Path.Combine(destination, file.Name), true);
}
}
}
}
我相信这部分是非常准确和有效的。但是,我的问题源于我的呼吁。
public static class Backup
{
public static void Save()
{
string[] drives = Directory.GetLogicalDrives();
foreach(string drive in drives)
{
DriveInfo diagnose = new DriveInfo(drive);
if(diagnose.VolumeLabel == @"Backup" && diagnose.DriveType == DriveType.Fixed)
{
CopyDirectory(
ConfigurationManager.AppSettings[@"Source"],
ConfigurationManager.AppSettings[@"Destination"]);
}
}
}
}
代码正在运行它此时看起来很顺利,它完成了正在复制的网站的百个目录中的五个,然后它随机抛出一个异常(为了简单,我留下了错误处理,但这是错误。)
IOException:设备尚未就绪。
随机停止阅读和撰写
我不完全确定为什么会这样,任何建议都会很棒。
答案 0 :(得分:3)
我建议只使用内置的FileSystem.CopyDirectory方法,该方法无需自定义代码即可正确处理目录复制。
答案 1 :(得分:2)
使用内置方法肯定更合适
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(source,destination,true);
但是,这不是问题的核心。问题是检查每个驱动器。具体而言,.VolumeLabel
上的DirectoryInfo
请求。您可以在MSDN上阅读有关该问题的一些背景知识:http://msdn.microsoft.com/en-us/library/system.io.driveinfo.volumelabel(v=vs.110).aspx
它分解的是,如果检查驱动器,它必须准备好。有时它没有准备好,当它在那时被访问时,你会得到一个例外
IOException - An I/O error occurred (for example, a disk error or a drive was not ready).
要解决此问题,请在使用diagnose.isReady
public static void Save()
{
string[] drives = Directory.GetLogicalDrives();
foreach(string drive in drives)
{
DriveInfo diagnose = new DriveInfo(drive);
if(diagnose.IsReady && diagnose.VolumeLabel == @"Backup" && diagnose.DriveType == DriveType.Fixed)
^^Make sure the drive is ready before examining properties
{
CopyDirectory(
ConfigurationManager.AppSettings[@"Source"],
ConfigurationManager.AppSettings[@"Destination"]);
}
}
}