【问题标题】:Directory.Delete(path,true) delete all the files and subdirectories but throw an exceptionDirectory.Delete(path,true) 删除所有文件和子目录但抛出异常
【发布时间】:2014-08-25 07:03:48
【问题描述】:

我使用 Directory.Delete(path,true) 方法删除目录。在删除之前,我用这个方法来检查文件夹是否可以删除:

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;
        }
    }

如果返回结果为真,则调用delete方法。我可以看到所有的文件和子目录都已经被删除了,但是方法抛出了一个异常,“进程无法访问文件'xxxxxxx'”。

如果无法删除整个文件夹,我希望删除操作不会删除文件夹中的任何文件。

【问题讨论】:

  • 我看到该函数将返回 true,即使您刚刚实例化了文件的 FileStream。它是一个局部变量,但我不确定垃圾收集器是否会及时释放它以进行下一次操作(删除调用)。您是否尝试过在返回 true 之前手动释放它?
  • @Havenard 我想这不是问题,因为using 确保处理流。

标签: c# file-io io


【解决方案1】:

尝试使用.NET Transactional File Manager

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2013-07-31
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多