无法删除VB.NET上的文件,因为另一个进程

时间:2015-11-25 12:22:33

标签: vb.net winforms

我在Visual Basic上创建一个Windows窗体应用程序,我在删除文件夹时遇到了一些困难。 用户选择一个文件,该文件首先使用DecryptFile()解密,然后在webbrowser webPreview上预览。 我希望我的程序在退出之前删除包含解密文件的文件夹(以及文件夹中的所有文件,而不进入回收站)。以下是选择文件时的代码:

Private Sub treFiles_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles treFiles.AfterSelect
    If (Not IO.Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\MyApp\" & lblUsername.Text & "\temp")) Then
        IO.Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\MyApp\" & lblUsername.Text & "\temp")
    End If
    DecryptFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\MyApp\" & lblUsername.Text & "\" & treFiles.SelectedNode.Text,
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\MyApp\" & lblUsername.Text & "\temp\" & treFiles.SelectedNode.Text, "AAAAAAAA")
    webPreview.Url = New Uri(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\MyApp\" & lblUsername.Text & "\temp\" & treFiles.SelectedNode.Text)
End Sub

这是DecryptFile()程序:

Public Sub DecryptFile(InputFile As String, OutputFile As String, key As String)
    Dim fsInput As New IO.FileStream(InputFile, IO.FileMode.Open, IO.FileAccess.Read)
    Dim fsDecrypted As New IO.FileStream(OutputFile, IO.FileMode.Create, IO.FileAccess.Write)
    Dim DES As New Security.Cryptography.DESCryptoServiceProvider
    DES.Key = Text.ASCIIEncoding.ASCII.GetBytes(key)
    DES.IV = Text.ASCIIEncoding.ASCII.GetBytes(key)
    Dim desdecrypt As Security.Cryptography.ICryptoTransform = DES.CreateDecryptor()
    Dim cryptostream As New Security.Cryptography.CryptoStream(fsInput, desdecrypt, Security.Cryptography.CryptoStreamMode.Read)
    Dim bytearrayinput(fsInput.Length - 1) As Byte
    cryptostream.Read(bytearrayinput, 0, bytearrayinput.Length)
    fsDecrypted.Write(bytearrayinput, 0, bytearrayinput.Length)
    fsInput.Close()
    cryptostream.Close()
    fsDecrypted.Close()
End Sub

以下是退出表单时执行的代码:

Private Sub frmHome_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
    webPreview.Url = Nothing
    IO.Directory.Delete(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\NeedForCrypt\" & lblUsername.Text & "\temp", True)
End Sub

问题是当我关闭应用程序时,Visual Studio给了我这个例外:

未处理的类型' System.IO.IOException'发生在mscorlib.dll

其他信息:该流程无法访问该文件' test.pdf'因为它正被另一个进程使用。

如何在退出时正确删除temp文件夹的文件?

1 个答案:

答案 0 :(得分:1)

您需要找出锁定文件的进程 - 尝试使用Microsoft Sysinternals' Process Explorer

如果您发现了哪个流程,可以尝试结束流程,或者如果结果是流程是您的vb程序,那么您需要仔细查看您的代码。

webPreview可能正在锁定文件 - 我认为可能就是这种情况 - 在您尝试删除文件之前,请尝试将浏览器指向http://localhost以释放对文件的锁定< / p>

相关问题