【发布时间】:2017-09-01 10:01:08
【问题描述】:
我正在尝试加密在我的应用程序中创建的.txt 文件。
要创建此文件,我使用以下代码:
Dim fileExists As Boolean = File.Exists(directorypath & "dbpw.txt")
If File.Exists(directorypath & "dbpw.txt") = False Then
Using sw As New StreamWriter(File.Open(directorypath & "dbpw.txt", FileMode.Create))
IIf(fileExists, "", "")
sw.Close()
End Using
End If
然后,为了编写和加密文件,我使用以下代码,调用我从互联网上的示例中调整的子例程。
bytKey = CreateKey(txtCode.Text)
bytIV = CreateIV(txtCode.Text)
EncryptOrDecryptFile(directorypath & "dbpw.txt", directorypath & "dbpw.txt", bytKey, bytIV, CryptoAction.ActionEncrypt)
当代码到达最后一行时,调用EncryptOrDecrypt 子例程,抛出一个错误提示
进程无法访问文件“myDirectoryPath\dbpw.txt”,因为它正被另一个进程使用
我需要做什么才能发布文件?
我也尝试只使用File.Create 和File.Encrypt,但无论哪种方式都会引发相同的错误。
EncryptOrDecryptFile() 的代码
Public Sub EncryptOrDecryptFile(ByVal strInputFile As String, ByVal strOutputFile As String, ByVal bytKey() As Byte, ByVal bytIV() As Byte, ByVal Direction As CryptoAction)
Try
fsInput = New System.IO.FileStream(strInputFile, FileMode.Open, FileAccess.Read)
fsOutput = New System.IO.FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write)
fsOutput.SetLength(0)
' Currently fails, file not being released for read/write once it's created.
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()
fsInput.Close()
fsOutput.Close()
Catch ex As Exception
errorLog(ex)
End Try
End Sub
【问题讨论】:
-
调用
sw.Close()是多余的,因为您将它包装在Using/End Using块中。至于您的问题,问题可能是基础流未关闭。而不是File.Open(),只需将文件名直接传递给StreamWriter:Using sw As New StreamWriter(directorypath & "dbpw.txt") -
@VisualVincent 我最初没有
sw.Close(),我只是添加它以查看它是否解决了问题。我按照您的建议将代码更改为Using sw As New StreamWriter(directorypath & "dbpw.txt", FileMode.Create),但仍然抛出相同的错误。 -
与问题无关,但
FileMode.Create在该上下文中无效。只需删除它并保留文件名。如果文件不存在,StreamWriter将创建该文件,如果存在则覆盖它。 -- 你是否在代码的其他地方使用/引用了这个文件? -
另外,我可以看看
EncryptOrDecryptFile()方法吗?可能是您尝试同时读取和写入同一个文件。 -
我怀疑...您正在为同一个文件打开
fsInput和fsOutput。一旦你打开了fsInput,它就会限制对文件的访问,这就是为什么你不能用写权限打开fsOutput。您必须为输出文件指定一个不同的名称或保留一个开放的加密流,每次将数据写入文件时都会使用它。
标签: vb.net encryption file-access