Directory.Delete(path, true) 总是给出错误 - ASP.NET 3.5 MVC

发布于 2024-08-21 01:59:11 字数 502 浏览 3 评论 0原文

我正在使用 MVC ASP.NET 3.5,并尝试使用我一直在 .NET 2.0 中使用的标准 .NET 方法删除包含所有文件的文件夹。

我发现这个但第一个答案似乎不起作用。
我已经尝试过这个

try
{
    Directory.Delete(path, true);
}
catch (IOException)
{
    Thread.Sleep(0);
    Directory.Delete(path, true);
}

并且有效,但我不明白为什么。
有什么建议吗?

编辑:我拥有权限,因为所有文件和子文件夹均已删除。但我有路径异常“目录非空”。如果我使用提供的代码,则可以正常工作,没有任何异常。

I'm using MVC ASP.NET 3.5 and I'm trying to delete a folder with all files within using standard .NET method that I've always used in .NET 2.0.

I found this but the first answer doesn't seem to work.
I've tried this one

try
{
    Directory.Delete(path, true);
}
catch (IOException)
{
    Thread.Sleep(0);
    Directory.Delete(path, true);
}

and works, but I can't understand why.
Any suggestions?

Edit: I've got permissions, because all files and sub-folders were deleted. But I've got and Exception "Directory is non-empty" with path. If I use the code provided, works without any exceptions.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

慈悲佛祖 2024-08-28 01:59:11

即使使用资源管理器,有时也会显示此消息(至少对我来说)。先删除文件再删除文件夹怎么样?

string[] files = Directory.GetFiles(some_path, "", SearchOption.AllDirectories);
foreach (string pathFile in files)
{
    File.Delete(pathFile);
}
Directory.Delete(some_path);

如果您有子文件夹,则可以使用 SearchOptions,但如果没有,则只需使用

string[] files = Directory.GetFiles(some_path);

希望这会有所帮助。

编辑

发生此问题的原因有很多(来吧,MS),但我认为主要是:因为文件夹已损坏或某些进程锁定它并阻止删除。

一个不优雅的解决方案可能是:先删除文件,然后删除子文件夹,最后一步删除主文件夹。

Even using the explorer this message is shown sometimes (at least for me). How about deleting the files first and then delete the folder?

string[] files = Directory.GetFiles(some_path, "", SearchOption.AllDirectories);
foreach (string pathFile in files)
{
    File.Delete(pathFile);
}
Directory.Delete(some_path);

you can use SearchOptions if you have subfolers but if not, then use simply

string[] files = Directory.GetFiles(some_path);

Hope this helps.

EDIT

This problem happens for many reasons(c'mon its MS), but I think the main are: because the folder is corrupted or some process is locking it and prevents the deletion.

A non elegant solution could be: delete the files first, then the subfolders, and the last step delete the main folder.

携君以终年 2024-08-28 01:59:11

尝试使用它对我有用

  File.SetAttributes(DownloaddirPath & "\" & directoryName, FileAttributes.Normal)
  Directory.Delete(DownloaddirPath & "\" & directoryName, True)

Try using this it worked for me

  File.SetAttributes(DownloaddirPath & "\" & directoryName, FileAttributes.Normal)
  Directory.Delete(DownloaddirPath & "\" & directoryName, True)
涙—继续流 2024-08-28 01:59:11

您有足够的权限删除该文件夹吗?另外,正如另一个问题所说,请确保该目录为空。

Do you have enough permissions to delete the folder? Also, as the other question says make sure that the directory is empty.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文