End of Stream encountered before parsing was completed. while Deserializing in vb.net - vb.net

I am getting error:
End of Stream encountered before parsing was completed while deserializing the file
code:
Dim fs As FileStream = Nothing
Try
fs = IO.File.OpenRead(Filename)
'fs = New FileStream(Filename, FileMode.Open)
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.AssemblyFormat = Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full
bf.TypeFormat = Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded
fs.Seek(0, SeekOrigin.Begin)
Dim obj As Object = bf.Deserialize(fs)
Return obj
Catch ex As Exception
MsgBox("There was an exception while trying to convert binary file to object. Exception: " & ex.Message & " | Stacktrace: " & ex.StackTrace)
Finally
If fs IsNot Nothing Then
fs.Close()
End If
End Try
I have tried with fs.Position=0 also even it is not working.
Any one can help me. Thanks in advance

The error is probably in serializing part of code.
Please for now get rid of Format properties in both procedures and make sure you were using using everywhere where possible so that all bytes of all streams, writers, readers and their wrappers have been flushed.

Related

End of Stream encountered before parsing was completed while deserializing

I am getting above error while deserializating BinaryFile to Object. I have tried set position=0, seek.begin method and tried with memory stream but no use. Every time i am getting same issue. Can anybody help me out?. Below is my code snippet for serialization and deserialization
Serialization
Dim fs As New FileStream(Filename, FileMode.OpenOrCreate)
Try
'fs = New FileStream(Filename, FileMode.OpenOrCreate)
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.AssemblyFormat = Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full
bf.TypeFormat = Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded
bf.Serialize(fs, data)
Catch ex As Exception
MsgBox("Exception: " & ex.Message & " | Stacktrace: " & ex.StackTrace)
Finally
fs.Flush()
fs.Close()
fs.Dispose()
End Try
Deserialization
Dim fs As FileStream = Nothing
Try
fs = IO.File.OpenRead(Filename)
'fs = New FileStream(Filename, FileMode.Open)
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.AssemblyFormat = Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full
bf.TypeFormat = Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded
fs.Seek(0, SeekOrigin.Begin) 'fs.Position=0
Dim obj As Object = bf.Deserialize(fs)
Return obj
Catch ex As Exception
MsgBox("There was an exception while trying to convert binary file to object. Exception: " & ex.Message & " | Stacktrace: " & ex.StackTrace)
Finally
If fs IsNot Nothing Then
fs.Flush()
fs.Close()
fs.Dispose()
End If
End Try

Getting exception while converting Filestream to binary in Deserialization process

Binary stream '48' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization
Dim fs As FileStream = Nothing
Try
fs = IO.File.OpenRead(Filename)
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.AssemblyFormat = Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full
bf.TypeFormat = Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded
fs.Position = 0
Dim obj As Object = bf.Deserialize(fs)
Return obj
Catch ex As Exception
MsgBox("There was an exception while trying to convert binary file to object. Exception: " & ex.Message & " | Stacktrace: " & ex.StackTrace)
Finally
If fs IsNot Nothing Then
fs.Close()
End If
End Try
Can anyone help me out.

Object reference not set to an instance of an object. Unable to read file and encrypt it [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I am new to VB.Net.
I am trying to read a text file, encrypt it and save the encrypted text file. However when I start the encrypt process, I get a System.NullReferenceException error.
Private Sub encryptOrDecrypt(ByVal strInputFile As String, ByVal strOutputFile As String, _
ByVal byteKey() As Byte, ByVal byteInitializationVector() As Byte, _
ByVal Process As CryptoProcess)
Try
'File stream for handling file IO
fileStreamInput = New System.IO.FileStream(strInputFile, FileMode.Open, FileAccess.Read)
fileStreamOutput = New System.IO.FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write)
'Ensure that output file is empty
fileStreamOutput.SetLength(0)
'Declaring variables for encryption and decryption process
Dim byteBuffer(4096) As Byte
Dim bytesProcessed As Long = 0
Dim fileLength As Long = fileStreamInput.Length
Dim intBytesInCurrentBlock As Integer
Dim csCryptoStream As CryptoStream
Dim cryptoRijnadel As New System.Security.Cryptography.RijndaelManaged
Select Case Process
Case CryptoProcess.EncryptFile
csCryptoStream = New CryptoStream(fileStreamOutput, _
cryptoRijnadel.CreateEncryptor(byteKey, byteInitializationVector), _
CryptoStreamMode.Write)
Case CryptoProcess.DecryptFile
csCryptoStream = New CryptoStream(fileStreamOutput, _
cryptoRijnadel.CreateDecryptor(byteKey, byteInitializationVector), _
CryptoStreamMode.Write)
End Select
While bytesProcessed < fileLength
intBytesInCurrentBlock = fileStreamInput.Read(byteBuffer, 0, 4096)
csCryptoStream.Write(byteBuffer, 0, intBytesInCurrentBlock)
bytesProcessed = bytesProcessed + CLng(intBytesInCurrentBlock)
End While
csCryptoStream.Close()
fileStreamInput.Close()
fileStreamOutput.Close()
If Process = CryptoProcess.EncryptFile Then
Dim fileOriginal As New FileInfo(strFileToEncrypt)
fileOriginal.Delete()
End If
Dim Wrap As String = Chr(13) + Chr(10)
If Process = CryptoProcess.EncryptFile Then
MsgBox("Done", MsgBoxStyle.Information, "Done")
End If
Catch When Err.Number = 53
MsgBox("File not found", MsgBoxStyle.Exclamation, "Invalid File")
Catch
fileStreamInput.Close()
fileStreamOutput.Close()
End Try
End Sub
The debugger shows the error at the line fileStreamOutput.Close()
Please help.
The problem is likely the fact that the first line fails, so execution jumps to the Catch block before the fileStreamOutput variable gets set:
fileStreamInput = New System.IO.FileStream(strInputFile, FileMode.Open, FileAccess.Read)
fileStreamOutput = New System.IO.FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write)
The simplest solution would be to simply check if the variable is null before using it in the Catch block:
Catch
If fileStreamInput IsNot Nothing Then
fileStreamInput.Close()
End If
If fileStreamOutput IsNot Nothing Then
fileStreamOutput.Close()
End If
End Try
However, as Plutonix pointed out, a Using block would be simpler. It's also worth mentioning that you are doing some other VB6-ish things in this code where better alternatives exist in VB.NET. For instance, you are calling MsgBox rather than using the more functional MessageBox.Show. However, that's very minor. The most regrettable thing is your use of the Err object. That, I must say, goes beyond a simple disagreement in preference. That crosses the line into offending my sensibilities. The proper way to catch exceptions in VB.NET is to specify the type of the exception in the Catch statement. You should never use the Err object, ever.
Try
Using fileStreamInput As New System.IO.FileStream(strInputFile, FileMode.Open, FileAccess.Read)
Using fileStreamOutput As New System.IO.FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write)
' ...
End Using
End Using
Catch ex As FileNotFoundException
MessageBox.Show("File not found", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
If, however, you choose to not use the Using blocks, you should, at the very least, change the last Catch to Finally. Currently, it catches and eats all other exceptions, so if anything else goes wrong, nothing will know about it.

DirectoryNotFoundException was unhandled

I'm trying to make a new file and write binary in it but the below error occurred
Could not find a part of the path 'C:\Users\user\Documents...\bin\Debug\data\binary\admin.bin'.
Here is my code
Dim bw As BinaryWriter
dim pathBin As String = Application.StartupPath & "\binary"
Dim fileExist As Boolean
Try
bw = New BinaryWriter(New FileStream(pathBin & "\admin.bin", FileMode.create))
fileExist = True
Catch ex As IOException
MessageBox.Show(ex.Message & vbNewLine & "Cannot create file.")
End Try
bw.Close()
Your issue is the path you are using does not exist which will make FileStream quite upset. Try something like this before you use the FileStream:
If Not Directory.Exists(pathBin) Then
Directory.CreateDirectory(pathBin)
End If
This will ensure that if the directory does not exist then it is created ahead of time.

Creating and appending text to txt file in VB.NET

Using VB.NET, I am trying to create a text file if it doesn't exist or append text to it if exists.
For some reason, though it is creating the text file I am getting an error saying process cannot access file.
And when I run the program it is writing text, but how can I make it write on a new line?
Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim sw As StreamWriter
Dim fs As FileStream = Nothing
If (Not File.Exists(strFile)) Then
Try
fs = File.Create(strFile)
sw = File.AppendText(strFile)
sw.WriteLine("Start Error Log for today")
Catch ex As Exception
MsgBox("Error Creating Log File")
End Try
Else
sw = File.AppendText(strFile)
sw.WriteLine("Error Message in Occured at-- " & DateTime.Now)
sw.Close()
End If
Try this:
Dim strFile As String = "yourfile.txt"
Dim fileExists As Boolean = File.Exists(strFile)
Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
sw.WriteLine( _
IIf(fileExists, _
"Error Message in Occured at-- " & DateTime.Now, _
"Start Error Log for today"))
End Using
Don't check File.Exists() like that. In fact, the whole thing is over-complicated. This should do what you need:
Dim strFile As String = $#"C:\ErrorLog_{DateTime.Today:dd-MMM-yyyy}.txt"
File.AppendAllText(strFile, $"Error Message in Occured at-- {DateTime.Now}{Environment.NewLine}")
Got it all down to two lines of code :)
This should work for you without changing program logic (by not outputting "Start error" on the top of each file) like the other answers do :)
Remember to add exception handling code.
Dim filePath As String = String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
Dim fileExists As Boolean = File.Exists(filePath)
Using writer As New StreamWriter(filePath, True)
If Not fileExists Then
writer.WriteLine("Start Error Log for today")
End If
writer.WriteLine("Error Message in Occured at-- " & DateTime.Now)
End Using
You didn't close the file after creating it, so when you write to it, it's in use by yourself. The Create method opens the file and returns a FileStream object. You either write to the file using the FileStream or close it before writing to it. I would suggest that you use the CreateText method instead in this case, as it returns a StreamWriter.
You also forgot to close the StreamWriter in the case where the file didn't exist, so it would most likely still be locked when you would try to write to it the next time. And you forgot to write the error message to the file if it didn't exist.
Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim sw As StreamWriter
Try
If (Not File.Exists(strFile)) Then
sw = File.CreateText(strFile)
sw.WriteLine("Start Error Log for today")
Else
sw = File.AppendText(strFile)
End If
sw.WriteLine("Error Message in Occured at-- " & DateTime.Now)
sw.Close()
Catch ex As IOException
MsgBox("Error writing to log file.")
End Try
Note: When you catch exceptions, don't catch the base class Exception, catch only the ones that are releveant. In this case it would be the ones inheriting from IOException.
Why not just use the following simple call (with any exception handling added)?
File.AppendAllText(strFile, "Start Error Log for today")
EDITED ANSWER
This should answer the question fully!
If File.Exists(strFile)
File.AppendAllText(strFile, String.Format("Error Message in Occured at-- {0:dd-MMM-yyyy}{1}", Date.Today, Environment.NewLine))
Else
File.AppendAllText(strFile, "Start Error Log for today{0}Error Message in Occured at-- {1:dd-MMM-yyyy}{0}", Environment.NewLine, Date.Today)
End If
While I realize this is an older thread, I noticed the if block above is out of place with using:
Following is corrected:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filePath As String =
String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
Using writer As New StreamWriter(filePath, True)
If File.Exists(filePath) Then
writer.WriteLine("Error Message in Occured at-- " & DateTime.Now)
Else
writer.WriteLine("Start Error Log for today")
End If
End Using
End Sub
Try it this way:
Dim filePath As String =
String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
if File.Exists(filePath) then
Using writer As New StreamWriter(filePath, True)
writer.WriteLine("Error Message in Occured at-- " & DateTime.Now)
Else
writer.WriteLine("Start Error Log for today")
End Using
end if