简体   繁体   English

Directory.Delete(path,true)删除所有文件和子目录,但引发异常

[英]Directory.Delete(path,true) delete all the files and subdirectories but throw an exception

I use Directory.Delete(path,true) method to delete a directory. 我使用Directory.Delete(path,true)方法删除目录。 Before deleting, I use this method to check if the folder could be deleted: 删除之前,我使用此方法检查是否可以删除该文件夹:

private bool FileCanDelete(string path)
    {
        try
        {
            //if this does not throw exception then the file is not use by another program
            using (FileStream fileStream = File.OpenWrite(path))
            {
                if (fileStream == null)
                    return false;
            }
            return true;
        }
        catch (UnauthorizedAccessException uaex)
        {
            throw uaex;
        }
        catch
        {
            return false;
        }
    }

If the return result is true, call the delete method. 如果返回结果为true,则调用delete方法。 I can see all the files and subdirectories have already deleted, but the method throw an exception, "The process cannot access the file 'xxxxxxx'". 我可以看到所有文件和子目录都已删除,但是该方法引发了一个异常:“进程无法访问文件'xxxxxxx'”。

If the whole folder couldn't be deleted, I want the delete operation doesn't delete any file in the folder. 如果无法删除整个文件夹,我希望删除操作不删除该文件夹中的任何文件。

Try using .NET Transactional File Manager 尝试使用.NET事务性文件管理器

TxFileManager fileMgr = new TxFileManager();
using (TransactionScope scope1 = new TransactionScope())
{

    fileMgr.DeleteDirectory(path);
    scope1.Complete();
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM