我试图删除一堆文件,但有些文件被锁定(正在使用中)。我只是想编程跳过锁定的并继续运行,但操作系统(Windows7)每次尝试删除其中一个文件时都弹出一条消息并告诉我它正在使用中。我只想抑制错误并将文件留在那里并继续尝试删除其他文件。
我唯一的选择" FileIO.UIOption"是"所有"或者"仅错误",我想要"无"。
For Each foundFile As String In My.Computer.FileSystem.GetFiles(Application.StartupPath, FileIO.SearchOption.SearchTopLevelOnly, "*.old")
Try
My.Computer.FileSystem.DeleteFile(foundFile, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
Catch ex As Exception
End Try
Next
已解决 - 见下文
答案 0 :(得分:3)
第一步实际上是使用File.Delete,哈哈。
IO.File.Delete不会显示对话框,它只会以IOException的形式返回,因此只需更改已有的对话即可。
For Each foundFile As String In My.Computer.FileSystem.GetFiles(Application.StartupPath, FileIO.SearchOption.SearchTopLevelOnly, "*.old")
Try
IO.File.Delete(foundFile)
Catch ex As IO.IOException
' File is in use.
End Try
Next
答案 1 :(得分:1)
这是我最终使用的:
Private Sub delete_file()
Dim file_open As Boolean = False
Dim stream As FileStream = Nothing
For Each foundFile As String In My.Computer.FileSystem.GetFiles(Application.StartupPath, FileIO.SearchOption.SearchTopLevelOnly, "*.old")
file_open = False
Try
stream = File.Open(foundFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
Catch ex As Exception
If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then
file_open = True
End If
Finally
If Not IsNothing(stream) Then
stream.Close()
End If
End Try
If file_open = False Then
Try
My.Computer.FileSystem.DeleteFile(foundFile, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
Catch ex As Exception
End Try
End If
Next
End Sub
Private Shared Function IsFileLocked(exception As Exception) As Boolean
Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1)
Return errorCode = 32 OrElse errorCode = 33
End Function
我从这个问题的贡献和以下问题中得出: VB.NET Checking if a File is Open before proceeding with a Read/Write?
答案 2 :(得分:0)
这是一个为我工作的c#工作,你可以把它转换成VB并使用它br
protected virtual bool IsFileInUse(FileInfo file) { FileStream FS = null;
try
{
FS = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
//File Locked or in use
return true;
}
finally
{
if (FS != null)
FS.Close();
}
//return if file is in unlicked state
return false;
}