加密后文件被锁定

时间:2016-09-22 06:42:05

标签: vb.net

我有一个小应用程序,旨在通过一个文件夹并加密所有文件并删除未加密的版本。加密工作正常但当我删除文件时它被锁定。应用关闭后,该文件不再被锁定。我的代码是

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim path As String = Directory.GetCurrentDirectory()
    Dim parent As DirectoryInfo = Directory.GetParent(path)
    Dim completions As String = parent.FullName & "\Attachments_Completions"
    Dim di As New DirectoryInfo(completions)
    Dim fi As FileInfo() = di.GetFiles()
    Dim dra As FileInfo
    For Each dra In fi
        If dra.Name <> "Completions.txt" And dra.Name <> "Attachments.txt" Then
            Dim tmpFileName As String = String.Format("{0}\qqzr_{1}", dra.DirectoryName, dra.Name)
            Dim encryptedName As String = String.Format("{0}\{1}", dra.DirectoryName, dra.Name)
            FileSystem.Rename(String.Format("{0}\{1}", dra.DirectoryName, dra.Name), String.Format("{0}\qqzr_{1}", dra.DirectoryName, dra.Name))
            cryptFile(tmpFileName, encryptedName, False)
            File.Delete(tmpFileName)
        End if
    Next
End Sub

Sub cryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal switch As Boolean) 
    ' * Used to Encrypt or Decrypt a file
    ' ***********************************
    Dim sKey As String = "a2#R|+~"
    Try
        Dim DES As New DESCryptoServiceProvider()
        DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)

        'Read the input file into array
        Dim fsInput As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
        Dim bytearrayinput(fsInput.Length - 1) As Byte
        fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)

        'Define the crypto transformer
        Dim cryptoTransform As ICryptoTransform

        If switch Then
            cryptoTransform = DES.CreateEncryptor()
        Else
            cryptoTransform = DES.CreateDecryptor
        End If

        'Create the encrypting streams
        Dim fsEncrypted As New FileStream(sOutputFilename, FileMode.Create, FileAccess.Write)
        Dim cryptostream As New CryptoStream(fsEncrypted, cryptoTransform, CryptoStreamMode.Write)

        'Write the output file
        cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
        cryptostream.Close()
        cryptostream.Dispose()
        'Release the input file
        fsInput.Close()
        fsInput.Dispose()
        'Release the output file
        fsEncrypted.Close()
        fsEncrypted.Dispose()
    Catch ex As Exception
    End Try

End Sub

结束班

有人可以帮忙吗? 干杯 詹姆斯

2 个答案:

答案 0 :(得分:0)

只需添加此

即可
    Catch ex As Exception
        Debug.Write(ex.Message)
    End Try

......看看会发生什么......

答案 1 :(得分:0)

感谢您的回复。

我设法通过在File.Delete命令

之前添加File.SetAttributes(tmpFileName, FileAttributes.Normal)来解决问题