我想复制一个文件夹,我想先删除目标文件夹。
所以我要删除目标文件夹然后重新创建它然后复制文件。
问题是我得到 An unhandled exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll
尝试复制文件时。这是代码
static public void CopyFolder(string sourceFolder, string destFolder)
{
if (Directory.Exists(destFolder)) // check if folde exist
{
Directory.Delete(destFolder, true); // delete folder
}
Directory.CreateDirectory(destFolder); // create folder
string[] files = Directory.GetFiles(sourceFolder);
foreach (string file in files)
{
string name = Path.GetFileName(file);
string dest = Path.Combine(destFolder, name);
File.Copy(file, dest, true);
FileInfo fileinfo = new FileInfo(dest); // get file attrib
if (fileinfo.Attributes != FileAttributes.ReadOnly) // check if read only
File.SetAttributes(dest, FileAttributes.Normal);
}.......
我在这一行 FileInfo fileinfo = new FileInfo(dest);
中得到异常。
文件夹的创建似乎有延迟,同时我尝试将文件复制到其中。任何线索,问题是什么?完整的异常信息:
An unhandled exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll
Additional information: Could not find a part of the path 'C:\Users\joe\Desktop\destfolder\.buildpath'.
解决方案
正如好心人指出的那样,出现此异常的原因是我尝试在删除过程完成之前重新创建文件夹。
所以解决方法是删除后增加2行代码:
GC.收集();
GC.WaitForPendingFinalizers();
所以正确的代码是
static public void CopyFolder(string sourceFolder, string destFolder)
{
if (Directory.Exists(destFolder)) // check if folde exist
{
Directory.Delete(destFolder, true); // delete folder
GC.Collect(); // CODE ADDED
GC.WaitForPendingFinalizers(); // CODE ADDED
}
Directory.CreateDirectory(destFolder); // create folder
string[] files = Directory.GetFiles(sourceFolder);
foreach (string file in files)
{
string name = Path.GetFileName(file);
string dest = Path.Combine(destFolder, name);
File.Copy(file, dest, true);
FileInfo fileinfo = new FileInfo(dest); // get file attrib
if (fileinfo.Attributes != FileAttributes.ReadOnly) // check if read only
File.SetAttributes(dest, FileAttributes.Normal);
}.......
通过这种方式,您可以等待创建直到删除过程完成。 感谢大家,尤其是 Saeed。
最佳答案
我对您当前的解决方案感到困惑。 GC 与删除文件夹无关,它之所以有效,是因为在其中添加 GC 相关功能类似于添加 Thread.Sleep() 或 MessageBox。它只在偶然情况下起作用。
相反,您应该等到目录真正被删除,例如:
Directory.Delete(destFolder, true); // delete folder
while(Directory.Exists(destFolder))
{
Thread.Sleep(100);
}
只有在这段代码完成后,您才应该继续。
关于c# - 删除空文件夹并重新创建后出现 System.IO.DirectoryNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4216396/