Read and write to memorystream

inzo21

Well-known member
Joined
Nov 5, 2003
Messages
74
Hello All,

Im trying to encrypt the contents of a file directly to a memorystream and then return that stream from the function. Having some issues - mostly that no data actually goes into the memorystream. Here is the following code:

Public Function EncryptFileToStream(ByVal filename As String)
Try
Dim fsInput As New FileStream(filename, FileMode.Open, FileAccess.Read)
Dim inputData(CInt(fsInput.Length - 1)) As Byte
fsInput.Read(inputData, 0, CInt(fsInput.Length))
fsInput.Close()

Dim mystring As FileInfo = New FileInfo(filename)
Console.WriteLine("File length: " & mystring.Length)
Dim mstream As New MemoryStream(inputData.Length)
mstream.SetLength(0)
Console.WriteLine("Byte length: " & inputData.Length)

Dim csEncrypted As New CryptoStream(mstream, crpSym.CreateEncryptor(m_key, m_iv), CryptoStreamMode.Write)
csEncrypted.Write(inputData, 0, inputData.Length)
csEncrypted.FlushFinalBlock()
csEncrypted.Close()
Console.WriteLine("File Stream Created!")
Console.WriteLine("Stream length: " & mstream.Length)
Return mstream
Catch ex As Exception
Return Nothing
Console.WriteLine("File Encryption could not occur! Could not write to stream.")

End Try

End Function

The string passed to the function is the path to the file and it is valid and exists. I am able to encrypt directly to a file - but need to do it to a stream and then return the memorystream - which will be read from another function and serialized into a file on a remote server.

Anyone have any ideas as to why the mem stream contains no data after this.

thanx in advance,

inzo
 
May not resolve the issue in question but you should probably declare the function as
Code:
Public Function EncryptFileToStream(ByVal filename As String) as MemoryStream
(also putting option strict on at the top of the code module will catch these kinds of errors).

Also what happens if you remove the following line?
Code:
mstream.SetLength(0)
 
Back
Top