Issue when trying to retrieve binary word document from SQL Server, using VB.net.

  • Thread starter Thread starter Viravalo
  • Start date Start date
V

Viravalo

Guest
Hello guys, hope you are all good.

I have an issue when retrieving a word document form my sql database. I'll show...

https://social.msdn.microsoft.com/Forums/getfile/1401647

So, I show database info in a listview. "Cargar" make the user choose an office document to save it in database, you also chose a name. Once you save the file, you clic the object in the listview and automatically the ID will move to textbox "codigo". Finally you can save the document with the button "recuperar documento".

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim archivo As New OpenFileDialog
archivo.Filter = "Documento de Word|*.docx"
If archivo.ShowDialog = DialogResult.OK Then
txt_ruta.Text = archivo.FileName
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Private Shared Sub WriteBinaryFile(ByVal fileName As String, ByVal data As Byte())

' Comprobación de los valores de los parámetros.
'
If (String.IsNullOrEmpty(fileName)) Then _
Throw New ArgumentException("No se ha especificado el archivo de destino.", "fileName")

If (data Is Nothing) Then _
Throw New ArgumentException("Los datos no son válidos para crear un archivo.", "data")

' Crear el archivo. Se producirá una excepción si ya existe
' un archivo con el mismo nombre.
Using fs As New IO.FileStream(fileName, IO.FileMode.CreateNew, IO.FileAccess.Write)

' Crea el escritor para la secuencia.
Dim bw As New IO.BinaryWriter(fs)

' Escribir los datos en la secuencia.
bw.Write(data)

End Using

End Sub



Create a function to write data in sequence.


Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Try
Dim strPath As String
strPath = txt_ruta.Text
Dim ruta As New FileStream(strPath, FileMode.Open, FileAccess.Read)
Dim binario(ruta.Length) As Byte
ruta.Read(binario, 0, ruta.Length) 'Leo el archivo y lo convierto a binario
ruta.Close() 'Cierro el FileStream

Dim cnn As New SqlConnection(str_conexion)
Dim cmm As New SqlCommand("sp_mant_archivo", cnn)
cmm.CommandType = CommandType.StoredProcedure
cmm.Parameters.AddWithValue("@id", txt_codigo.Text)
cmm.Parameters.AddWithValue("@nombre", txt_nombre.Text)
cmm.Parameters.AddWithValue("@archivo", binario)
'ejecutar
Dim li As ListViewItem = ListView1.Items.Add(txt_codigo.Text)
li.SubItems.Add(txt_nombre.Text)
Try
cnn.Open()
cmm.ExecuteNonQuery()
MsgBox("Se Guardó Exitosamente")

Catch ex As Exception
MsgBox(ex.Message)
Finally
cnn.Dispose()
cmm.Dispose()
End Try
Catch ex As Exception

End Try
End Sub



Save Button


Dim data As Byte() = Nothing
Try
Using cnn As New SqlConnection("Data Source=Vic\Vic;Initial Catalog=DB_Archivo;Integrated Security=True")
Dim cmd As SqlCommand = cnn.CreateCommand()
cmd.CommandText = "SELECT archivo FROM TB_Archivo WHERE Id = " & txt_codigo.Text & " "
cnn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
dr.Read()
Dim bufferSize As Integer = Convert.ToInt32(dr.GetBytes(0, 0, Nothing, 0, 0))
data = New Byte(bufferSize - 1) {}
dr.GetBytes(0, 0, data, 0, bufferSize)
dr.Close()

End Using

Dim archivo As New SaveFileDialog
archivo.Filter = "All files (*.*)|*.*"
If archivo.ShowDialog = DialogResult.OK Then
txt_nombre.Text = archivo.FileName
WriteBinaryFile(txt_nombre.Text & ".docx", data)
' Process.Start(txt_nombre.Text & ".docx")
MsgBox("El archivo ha sido recuperado exitosamente")
End If

Catch ex As Exception
MessageBox.Show(ex.Message)

End Try
End Sub



Resave the file.


Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
ListView1.View = View.Details
ListView1.GridLines = True
Dim conn As New SqlConnection(strConnString)
Dim strQ As String = String.Empty
strQ = "SELECT id, Nombre from tb_archivo"
cmd1 = New SqlCommand(strQ, conn)
da = New SqlDataAdapter(cmd1)
ds = New DataSet
da.Fill(ds, "Table")

Dim i As Integer = 0
Dim j As Integer = 0

' adding the columns in ListView
For i = 0 To ds.Tables(0).Columns.Count - 1
ListView1.Columns.Add(ds.Tables(0).Columns(i).ColumnName.ToString())
Next
'Now adding the Items in Listview
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
ListView1.Items.Add(lvi)
ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
Next
Catch ex As Exception
MessageBox.Show($"Error: {ex.ToString}", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub

Listbox feeding.

Table: TB_Archivo

id: int

nombre: varchar(100)

archivo: varbinary(max)

https://social.msdn.microsoft.com/Forums/getfile/1401648

I get this warning once I save the document, "Word found not legible content, do you want to recover the content of this document?"

Once I choose yes "si", the document is there, nice and neat. It's just the warining which is bothering me. :s

Continue reading...
 
Back
Top