Convert From Byte[] to File - sql-server

I use the following Function to convert a file to Byte()
Public Function FileToByteArray(ByVal _FileName As String) As Byte()
Dim _Buffer() As Byte = Nothing
Try
' Open file for reading
Dim _FileStream As New System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)
' attach filestream to binary reader
Dim _BinaryReader As New System.IO.BinaryReader(_FileStream)
' get total byte length of the file
Dim _TotalBytes As Long = New System.IO.FileInfo(_FileName).Length
' read entire file into buffer
_Buffer = _BinaryReader.ReadBytes(CInt(Fix(_TotalBytes)))
' close file reader
_FileStream.Close()
_FileStream.Dispose()
_BinaryReader.Close()
Catch _Exception As Exception
' Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString())
End Try
Return _Buffer
End Function
I save the file ("C:\sample.xlsx") using this function to database(I use Microsoft SQL Server) as SqlDbType.Image
Below is the code that I use to get the value from db and try to convert it as a file again.
Dim FileInBinary() As Byte
Dim CurrentRS As Recordset
'Select
SQLString = "SELECT FileInBinary from table where ID=1"
'Get value to a recordSet
CurrentRS = ServerRunSQL_Return(SQLString)
'SaveValue to Dim
FileInBinary = CurrentRS.Fields(0).Value
'Try to convert
My.Computer.FileSystem.WriteAllBytes("C:\sample_new.xlsx", FileInBinary, True)
I also tried:
File.WriteAllBytes("C:\sample_new.xlsx", FileInBinary)
How can I select this value and convert it again as file ("C:\sample_new.xlsx")?

Replace the Function FileToByteArray with File.ReadAllBytes("C:\sample.xlsx")
Below is the code to get the value from db and convert it as a file again.
Dim FileInbinary As Byte()
SqlConn.Open()
Dim command As New SqlCommand("SELECT FileInBinary from table where ID=1", SqlConn)
FileInbinary = DirectCast(command.ExecuteScalar(), Byte())
SqlConn.Close()
File.WriteAllBytes("C:\sample_new.xlsx", FileInbinary)

Related

VB.NET | EMF File becomes plain white in crystal report, How to properly save emf file in sql server

After successfully converted a png file to emf file, another problem begins because when I tried to display the emf file in crystal report it became white.
The emf file was fetched in SQL Server.
I tried to export the data into the database, I found out that the emf file is blank. but I am pretty sure that the emf file I saved is not blank. so the main question is how to properly save an emf file in the database (SQL Server).
here is my code to save the image.
Dim SqlCom As SqlCommand
Dim imageData As Byte()
Dim sFileName As String
Dim qry As String
Try
If jonsqlcon.State = ConnectionState.Closed Then
jonsqlcon.Open()
End If
imageData = ReadFile(sFilePath)
sFileName = System.IO.Path.GetFileName(sFilePath)
qry = "INSERT INTO Signature (ControlNo,Sig) " & _
"VALUES(#ControlNo,#Sig)"
SqlCom = New SqlCommand(qry, jonsqlcon)
SqlCom.Parameters.Add(New SqlParameter("#ControlNo", TxtControlNo.Text))
SqlCom.Parameters.Add(New SqlParameter("#Sig", DirectCast(imageData, Object)))
SqlCom.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
and here is the ReadFile Function
Private Function ReadFile(ByVal sPath As String) As Byte()
Dim data As Byte() = Nothing
Dim fInfo As New FileInfo(sPath)
Dim numBytes As Long = fInfo.Length
Dim fStream As New FileStream(sPath, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fStream)
data = br.ReadBytes(CInt(numBytes))
Return data
End Function

Why image cannot be saved in database

I'm using VB.NET and SQL Server for my system. I have a problem saving an image into the database. I need to save and retrieve image on the same page but I get an error:
unable to cast System.DBNull to system bytes.
I have tried several coding to fix my coding but it does not worked.
Code for retrieve image.
Dim id As String = txtImages.Text.Trim() 'txtImages is textbox name
Image1.Visible = id <> ""
If id <> "" Then
Dim dt As DataTable = GetData((Convert.ToString("SELECT ImagePic FROM masterlist WHERE id
='") & Request.QueryString("id")) + "'") 'image data will be select depend on what user search in the
serch textbox
If dt.Rows.Count > 0 Then
Dim bytes As Byte() = TryCast(dt.Rows(0)("ImagePic"), Byte())
Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
Image1.ImageUrl = Convert.ToString("data:images/png;base64,") & base64String
Else
Image1.ImageUrl = ""
Image1.AlternateText = "No image present in database with the name" 'if there is no image
in db the message will displayed
End If
End If
End Sub
Code for save image
Dim fileName As String = String.Empty
Dim filePath As String = String.Empty
Dim getPath As String = String.Empty
Dim pathToStore As String = String.Empty
Dim bytes As [Byte]()
Dim fs As FileStreamenter code here
Dim br As BinaryReader
Dim cmd As New SqlCommand("Updateonlyimage_Sp3", cs) ' SQL command for this page is inside SQL Server I declare it as Insertapprovalcustom_Sp2"
cmd.CommandType = CommandType.StoredProcedure
Try
If FileUpload1.HasFile Then
fileName = FileUpload1.FileName
filePath = Server.MapPath("HSCODE/" & Convert.ToString(System.Guid.NewGuid()) & fileName)
'path to doucument inside approval_pdf file
FileUpload1.SaveAs(filePath)
cmd.Parameters.AddWithValue("#id", Request.QueryString("id"))
cmd.Parameters.AddWithValue("#ImagePicName", fileName)
Dim getPos As Integer = filePath.LastIndexOf("\")
Dim len As Integer = filePath.Length()
getPath = filePath.Substring(getPos, len - getPos)
pathToStore = getPath.Remove(0, 1)
cmd.Parameters.AddWithValue("#ImagePicPath", pathToStore)
fs = New FileStream(filePath, FileMode.Open, FileAccess.Read)
br = New BinaryReader(fs)
bytes = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
cmd.Parameters.AddWithValue("#ImagePic", bytes)
cmd.Parameters.AddWithValue("#ContentType", FileUpload1.PostedFile.ContentType)

iTextSharp generating corrupted PDF in WPF

I am new to programming with iTextSharp. i have an application that writes in PDF file. File is written in word and than saved in PDF (there are 2 pages). My problem is, that when I want to write on PDF I see the data that was written on but the output PDF is corrupted. I don't understand why PDF gets corrupted?
Public Sub WriteForm(TemplateFilePath As String, NewFilePath As String, data As FormData)
'input output files
Dim oldFile As String = TemplateFilePath
Dim newFile As String = NewFilePath
'if file already exists then delete it
If System.IO.File.Exists(newFile) Then
System.IO.File.Delete(newFile)
End If
' open the reader
Dim reader As New PdfReader(oldFile)
Dim size As Rectangle = reader.GetPageSizeWithRotation(1)
Dim document As New Document(size)
' open the writer
Dim fs As New FileStream(newFile, FileMode.Create, FileAccess.Write)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, fs)
document.Open()
'write data to first page
Me.WriteData(reader, writer, data)
'write second page
Me.AppendCopiedPage(document, writer, reader, 2)
' close the streams
document.Close()
fs.Close()
writer.Close()
reader.Close()
End Sub
'code for WriteData
Private Sub WriteData(reader As PdfReader, writer As PdfWriter, data As FormData)`
Dim cb As PdfContentByte = writer.DirectContent
Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED)
cb.SetColorFill(BaseColor.BLACK)
cb.SetFontAndSize(bf, 10)
' create the first page and add it to the pdf
Dim page1 As PdfImportedPage = writer.GetImportedPage(reader, 1)
cb.AddTemplate(page1, 0, 0)
Me.WriteText(cb, data.SID, 110, 653)
...
End Sub

Unzip a zip file in silverlight

I am trying to develop code to unzip file from the zip file in Silverlight 5. The files are in a directory within the zip file.
I translated this code I found elsewhere from c# to VB since we are a VB shop. It is failing on the fourth line "Object reference not set to an instance of an object.".
I realize now that the problem is that the third line is expecting a relative uri and I am passing it a file, but I don't know how to fix this.
Can you tell me what is wrong with this code. I will also welcome other ideas.
Thanks.
Public Shared Function GetZipContents(ByVal filename As String) As String()
Try
Dim zipStream As System.IO.Stream = New System.IO.MemoryStream()
Dim zipInfo As New StreamResourceInfo(zipStream, Nothing)
Dim streamInfo As StreamResourceInfo = Application.GetResourceStream(zipInfo, New Uri(filename, UriKind.Relative))
Dim fileStream As Stream = streamInfo.Stream
Dim names As New List(Of String)()
Dim reader As New BinaryReader(fileStream)
Do While reader.ReadUInt32() = &H4034B50
' Skip the portions of the header we don't care about
reader.BaseStream.Seek(14, SeekOrigin.Current)
Dim compressedSize As UInteger = reader.ReadUInt32()
Dim uncompressedSize As UInteger = reader.ReadUInt32()
Dim nameLength As Integer = reader.ReadUInt16()
Dim extraLength As Integer = reader.ReadUInt16()
Dim nameBytes() As Byte = reader.ReadBytes(nameLength)
names.Add(Encoding.UTF8.GetString(nameBytes, 0, nameLength))
reader.BaseStream.Seek(extraLength + compressedSize, SeekOrigin.Current)
Loop
' Move the stream back to the begining
fileStream.Seek(0, SeekOrigin.Begin)
Return names.ToArray()
Catch ex As Exception
MessageBox.Show(ex.Message)
Return Nothing
End Try
End Function
There is quick and dirty way to unzip in Silverlight.
Use Application.GetResourceStream Method.
http://msdn.microsoft.com/en-us/library/cc190632(v=vs.95).aspx
Check out my blogpost on this: http://www.sharpgis.net/post/2010/08/25/REALLY-small-unzip-utility-for-Silverlight-e28093-Part-2.aspx
Sorry I would have time to explore the suggestions. I did find a way to accomplish my goal on my own. See the code below. I would be using this code either because the Technical Leader here prefers I do it a different way using a WCF service. Warning I was not able to test this code 100% since I am not planning to use it, but it is close to being right.
Imports ICSharpCode.SharpZipLib.Zip
Public Shared Sub UnZip(ByVal SrcFile As String, ByVal DstFile As String, ByVal BufferSize As Integer)
Try
Dim _FileName As String
Dim _ZipEntry As ZipEntry
Dim _FileStreamOut As FileStream = Nothing
Dim _Done As Boolean = False
Dim _FileStreamIn As New FileStream(SrcFile, FileMode.Open, FileAccess.Read)
Dim _ZipInStream As New ZipInputStream(_FileStreamIn)
Do Until _Done = True
_ZipEntry = _ZipInStream.GetNextEntry()
If IsNothing(_ZipEntry) Then
_Done = True
Exit Do
End If
_FileName = DstFile & "\" & _ZipEntry.Name
_FileName = _FileName.Replace("/", "\")
If Right(_FileName, 1) = "\" Then
If Directory.Exists(_FileName) = False Then
Directory.CreateDirectory(_FileName)
End If
Else
_FileStreamOut = New FileStream(_FileName, FileMode.Create, FileAccess.Write)
Dim size As Integer
Dim buffer(BufferSize - 1) As Byte
Do
size = _ZipInStream.Read(buffer, 0, buffer.Length)
_FileStreamOut.Write(buffer, 0, size)
Loop While size > 0
End If
Loop
_ZipInStream.Close()
_FileStreamOut.Close()
_FileStreamIn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

How to store and retrieve images in sql server database through VB.NET

SQL Server supports the ability for clients to store
objects within tables.
Create Field that data type Image and Initialize byte array with a null value initially.Use FileInfo object to get file size.Open FileStream to read file.Use
Do a little googling before posting here. Below is the third search result I got for your query. I know how to do this, but not enough patience to do it again. So here is a sample code from TechArena
Function SaveImage _
(ByVal FileName As String) As Integer
' Create a FileInfo instance
' to retrieve the files information
Dim fi As New FileInfo(FileName)
' Open the Image file for Read
Dim imgStream As Stream = _
fi.OpenRead
' Create a Byte array the size
' of the image file for the Read
' methods buffer() byte array
Dim imgData(imgStream.Length) As Byte
imgStream.Read(imgData, 0, fi.Length)
Dim cn As New SqlConnection _
(ConfigurationSettings.AppSettings("cn"))
Dim cmd As New SqlCommand("Images_ins", cn)
cmd.CommandType = CommandType.StoredProcedure
With cmd.Parameters
.Add("#FileName", VarChar, 100).Value = _
fi.Name
.Add("#FileType", VarChar, 10).Value = +
fi.Extension
.Add("#Image", Image).Value = imgData
.Add("#FileSize", Int, 4).Value = fi.Length
End With
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
cn.Dispose()
End Function
The image field in SQL Server is simply a byte array. Here is the significant code you will need. Let's assume the name of your image field in the database is "imageField". Hope this helps.
To retrieve an image and save it to disk:
//dr is a DataReader returned from a SELECT command
Dim imageInBytes As Byte() = dr("imagefield")
Dim memoryStream As System.IO.MemoryStream = _
New System.IO.MemoryStream(imageInBytes, False)
Dim image As System.Drawing.Image = _
System.Drawing.Image.FromStream(memoryStream)
image.Save("c:\image")
To save an image into SQL Server from disk:
''Get the image file into a Byte Array
Dim image As Byte() = System.IO.File.ReadAllBytes("c:\image.jpg")
''Add the byte array as a parameter to your Insert/Update SQLCommand
parameters.Add("#ImageField", image)

Resources