yos*_*ssi 15 c# copy exception file
我想复制一个文件夹,我想先删除目标文件夹.所以我删除目标文件夹然后重新创建它,然后复制文件.问题是我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);
}.......
Run Code Online (Sandbox Code Playgroud)
我在这一行得到了例外FileInfo fileinfo = new FileInfo(dest);.
似乎文件夹的创建有延迟,同时我尝试将文件复制到其中.有任何线索,有什么问题?完整的异常消息:
mscorlib.dll中发生未处理的"System.IO.DirectoryNotFoundException"类型异常
附加信息:找不到路径'C:\ Users\joe\Desktop\destfolder\.buildpath'的一部分.
正如好人所指出的,这个例外的原因是我尝试在删除过程完成之前重新创建文件夹.因此解决方案是在删除后添加2行代码:
GC.Collect();
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);
}.......
Run Code Online (Sandbox Code Playgroud)
这样,您等待创建,直到删除过程完成.Yhanks所有人,特别是Saeed.
我对您当前的解决方案感到困惑。GC 与删除文件夹无关,它仅起作用是因为添加 GC 相关功能类似于添加 Thread.Sleep() 或 MessageBox。它只是偶然起作用。
相反,您应该等到目录被实际删除,例如:
Directory.Delete(destFolder, true); // delete folder
while(Directory.Exists(destFolder))
{
Thread.Sleep(100);
}
Run Code Online (Sandbox Code Playgroud)
只有在此代码完成后,您才应该继续。
Yoc*_*mer -1
你搞错了。异常的原因是仍然有资源正在访问该文件夹(或文件)。
解决方案永远GC.collect()不是Sleep()……这只是一种解决方法。您所做的只是让垃圾收集器处理资源,然后给它时间采取行动。
正确的方法是管理自己的资源。不要使用您无法控制的静态方法,而是使用using块并在块末尾释放资源。这样,您在等待不受您控制的事情 (GC) 时就不会产生任何开销。
使用控制资源的对象,using块将在最后处理它。
在您的情况下,使用控制该资源的单个DirectoryInfo对象应该可行。