vb.net 无法删除文件。另一个进程正在使用的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15483190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:51:26  来源:igfitidea点击:

Can't delete file. File in use by another process

vb.net

提问by m.cichacz

I have a program (simple file updater) which downloads a file. Before that, an old version of this file is queued for deletion. But if I edit this file e.g. in text editor (save and close it), then my program refuses to delete it.

我有一个下载文件的程序(简单的文件更新程序)。在此之前,该文件的旧版本已排队等待删除。但是如果我在文本编辑器中编辑这个文件(保存并关闭它),那么我的程序拒绝删除它。

I have sub like this

我有这样的子

Private Sub delete_file(ByVal dir As String)
    Try
        If My.Computer.FileSystem.FileExists(dir) Then My.Computer.FileSystem.DeleteFile(dir)
    Catch ex As Exception
        Debug.WriteLine(ex.ToString())
        Sleep(1000)
        delete_file(dir)
    End Try
End Sub

It never goes out of the recursion. Exception says that file is being used by other process, and waiting doesn't change anything. Any clues?

它永远不会退出递归。异常表示该文件正在被其他进程使用,并且等待不会改变任何内容。有什么线索吗?

[EDIT] Changed Sub a bit, so it doesn't contain recursion in Exception handler

[编辑] 稍微更改了 Sub,因此它在异常处理程序中不包含递归

Private Sub delete_file(ByVal dir As String)
    Dim ok As Boolean = True
    Try
        If My.Computer.FileSystem.FileExists(dir) Then My.Computer.FileSystem.DeleteFile(dir)
    Catch ex As Exception
        Debug.WriteLine(ex.ToString())
        ok = False
    End Try

    If ok = False Then
        Sleep(1000)
        delete_file(dir)
    End If

End Sub

回答by m.cichacz

Words "another process" are VERY ambiguous.

“另一个过程”这个词非常含糊。

It turned out that other function from my program was opening the same file twice, and closing it only once. Fixing that removed problem with deleting it.

结果是我程序中的其他函数打开同一个文件两次,只关闭一次。通过删除它来修复已删除的问题。

So when u're having the same error, try searching your program for other places when this file may be modified.

因此,当您遇到相同的错误时,请尝试在可能修改此文件的其他地方搜索您的程序。

Thanks for comments, they surely gave me some hints about good programming.

感谢您的评论,他们肯定给了我一些关于良好编程的提示。