在VB.NET中解密文件,正在使用中

时间:2015-12-31 20:17:43

标签: vb.net encryption

我试图使用以下代码在VB中解密文件:

Try
            fsInput = New System.IO.FileStream(strInputFile, FileMode.Open, FileAccess.Read)
            fsOutput = New System.IO.FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write)
            fsOutput.SetLength(0)
            Dim bytBuffer(4096) As Byte
            Dim lngBytesProcessed As Long = 0
            Dim lngFileLength As Long = fsInput.Length
            Dim intBytesInCurrentBlock As Integer
            Dim csCryptoStream As CryptoStream
            Dim cspRijndael As New System.Security.Cryptography.RijndaelManaged
            Select Case Direction
                Case CryptoAction.ActionEncrypt
                    csCryptoStream = New CryptoStream(fsOutput, _
                    cspRijndael.CreateEncryptor(bytKey, bytIV), _
                    CryptoStreamMode.Write)
                Case CryptoAction.ActionDecrypt
                    csCryptoStream = New CryptoStream(fsOutput, _
                    cspRijndael.CreateDecryptor(bytKey, bytIV), _
                    CryptoStreamMode.Write)
            End Select
            While lngBytesProcessed < lngFileLength
                intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096)
                csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock)
                lngBytesProcessed = lngBytesProcessed + CLng(intBytesInCurrentBlock)
            End While
            csCryptoStream.Close()
        Catch ex As Exception
            Clipboard.SetText(ex.ToString)
        End Try
        fsInput.Close()
        fsOutput.Close()

这是我现在得到的错误:

System.IO.IOException: The process cannot access the file 'C:\Users\suffICE\Desktop\asdas.icevault' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
   at IceVaultFileOpener.Cryptography.fileCrypt.EncryptOrDecryptFile(String strInputFile, String strOutputFile, Byte[] bytKey, Byte[] bytIV, CryptoAction Direction) in F:\IceVault Developer Directory\IceVaultFileOpener\IceVaultFileOpener\icevaultfile.vb:line 91

我已经检查过是否可以在任何其他程序中打开文件,但事实并非如此。我怎样才能解决这个问题?感谢。

1 个答案:

答案 0 :(得分:1)

您需要将fileshare参数添加到open语句中。输出文件上的FileShare.Read选项之类的东西。如果没有该参数,它们将以独占模式打开。

另外,将.Close()语句放在End Try语句之后,以便无论发生什么情况它们都会被关闭。此外,请确保您实际上没有捕获此例程中的错误,从而跳过关闭文件,以便在您尝试解密时,它尚未被SAME进程打开。 (假设您正在尝试加密,并在同一程序中解密,仅用于测试等...)