在我的应用程序中,我构建了一个系统,用户可以在其中创建图片库。照片以 category_name/gallery_name/{pictures} 格式保存在磁盘上的文件夹中。每张上传的照片都存储在上面给出的相关目录结构下。
但是,在尝试删除类别以及从数据库中删除时,我也想从系统中删除相关文件夹。当我第一次收到错误消息“目录不为空”时,我搜索并找到了这个解决方案:
public static void DeleteDirectory(string target_dir)
{
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(target_dir, false);
}
使用此解决方案,“gallery_name”文件夹中的照片会被很好地删除,然后gallery_name 文件夹本身会被很好地删除。所以我们现在只剩下一个空的category_name 文件夹。然后调用上述子例程 ( Directory.Delete(target_dir, false);
) 中的最后一段代码来删除 category_name 文件夹。错误再次引发..
有谁知道解决这个问题?
Directory.Delete(target_dir, true);
没用,这就是我尝试替代方案的原因。- 我可以完全控制父文件夹,并且 category_name 和 gallery_name 文件夹也是以编程方式创建的,没有任何问题。
- 正如我所提到的,使用此代码删除子目录(gallery_name 文件夹)及其内容(照片)就好了。导致错误的是 category_name 文件夹,即使在此代码之后,它只是一个空文件夹。
我得到的异常消息是:
System.IO.IOException was unhandled by user code
HResult=-2147024751
Message=The directory is not empty.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive, Boolean throwOnTopLevelDirectoryNotFound)
at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive, Boolean checkHost)
at System.IO.Directory.Delete(String path)
at MyApp.PhotoGallery.Categories.deleteCategory(Int32 cID, String categoryname) in d:\Documents\My Dropbox\web projects\MyAppFolder\App_Code\BLL\PhotoGallery.vb:line 291
at _admhades_PhotoGallery.deleteCategory(Int32 categoryID, String categoryname) in d:\Documents\My Dropbox\web projects\HavadisPre\_admhades\PhotoGallery.aspx.vb:line 71