Recover Files from the SQL Server Database

0

Context

This is the Structure of my Project:

By clicking on the DatagridView the "Id", the name, and the extension are stored in variables that go as parameters to the functions

In the form, what I want is only to keep it in the folder that I specify. I tried it myself, giving it the route manually with code and if it works for me, I would like it to work in the graphical way.

I searched the internet for something related to that and I found what I should do but I do not understand very well

Error

To save files I have no problem. At the time of saving send me this message:

By using FolderBrowserDialog1 of Visual.net, I select the path in which I want to save my file.

Code

This is the code when you press the button to select the folder

Private Sub Button4_Click_1(sender As Object, e As EventArgs) Handles Button4.Click

    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        txtcarpeta.Text = FolderBrowserDialog1.SelectedPath

    End If
End Sub

This code is to register

 Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Try

        fun = New DArchivo
        If fun.descargar(id, extension, txtcarpeta.Text, nom) Then
            MsgBox("Listo")
        Else
            MsgBox("No listo")
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

This is my Conexion class

Imports System.Data.SqlClient
Public Class Miconexion
Dim cone As New SqlConnection(My.Settings.Miconexion)

Public Function conectar() As SqlConnection
    Try
        cone.Open()
        Return cone
    Catch ex As Exception
        MsgBox(ex.Message)
        Return Nothing
    End Try
End Function
Public Function desconectar() As SqlConnection
    Try
        If cone.State = ConnectionState.Open Then
            cone.Close()
        End If
        Return cone
    Catch ex As Exception
        Return Nothing
    End Try
End Function
End Class

this is my class of Functions to register show and those things

Public Class DArchivo
Private conex As Miconexion
Dim cmd As SqlCommand ''recibe el comando SQL SErver
Dim da As New SqlDataAdapter ''Adaptaa el comando para que el visual lo entienda
Dim tabla As New DataTable
Public Function ReadBinaryFile(ByVal fileName As String) As Byte()

    ' Generar una excepción si no existe el archivo.
    '
    If (Not IO.File.Exists(fileName)) Then
        Throw New IO.FileNotFoundException("No existe el archivo especificado.")
    End If

    ' Leer el archivo especificado devolviendo una matriz de bytes con su contenido.
    '
    Return IO.File.ReadAllBytes(fileName)

End Function
Public Function REGISTRARARCHIVO(ByVal nombre As String, ByVal ext As String, ByVal fila As String) As Boolean
    Try
        Dim blob As Byte() = ReadBinaryFile(fila)

        conex = New Miconexion
        cmd = New SqlCommand("Sp_RegArchivo", conex.conectar())
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@nombre", nombre)
        cmd.Parameters.AddWithValue("@extenssion", ext)
        cmd.Parameters.AddWithValue("@fila", If(blob IsNot Nothing, blob, CObj(DBNull.Value)))

        If cmd.ExecuteNonQuery Then
            Return True
        Else
            Return False
        End If

        Return True
    Catch ex As Exception
        MsgBox(ex.Message)
        Return False
    Finally
        conex.desconectar()
    End Try
End Function

Public Function MOSTRARARCHIVO() As DataTable
    Try
        conex = New Miconexion
        cmd = New SqlCommand("Sp_MostrarArchivo", conex.conectar())
        da = New SqlDataAdapter(cmd)

        tabla.Clear()
        da.Fill(tabla)
        Return tabla

    Catch ex As Exception
        MsgBox(ex.Message)
        Return Nothing
    Finally
        conex.desconectar()
    End Try
End Function
Public Function descargar(ByVal id As String, ByVal ext As String, ByVal ruta As String, ByVal nombre As String) As Boolean
    Try
        conex = New Miconexion
        cmd = New SqlCommand("MuestraArchivo", conex.conectar())
        da = New SqlDataAdapter(cmd)
        tabla.Clear()
        da.Fill(tabla)

        If tabla.Rows.Count = 0 Then
            MsgBox("No hasy DAtos")
        Else
            id = tabla.Rows(0).Item("IdArchivo")
            Dim res As Byte() = tabla.Rows(3).Item("Fila")
            File.WriteAllBytes(ruta & ext, res)
        End If
        Return True
    Catch ex As Exception
        MsgBox(ex.Message)
        Return False
    End Try
End Function
End Class

Entire form

Imports System.Security.Permissions

Public Class Archivos
    Dim fun As DArchivo
    Dim extension, nombreArchivo, id, nom As String

    Public Property ruta As String



    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim openfile As New OpenFileDialog()
        Dim nombre As String
        Try
            openfile.Filter = "Archivos de Texto (*.txt)|*.txt|Archivos de Imagen (*.jpg,*.png,*.bmp,*.gif)|*.jpg;*.png;*.bmp;*.gif|All Files (*.*)|*.*"
            If openfile.ShowDialog = Windows.Forms.DialogResult.OK Then

                nombre = openfile.FileName

                txtruta.Text = nombre
            End If
        Catch ex As Exception
            MsgBox("Debe elegir una imagen", MsgBoxStyle.Exclamation, "HogarSoft")
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Try
            obtenerNombreExtension()
            fun = New DArchivo
            fun.ReadBinaryFile(txtruta.Text)
            If fun.REGISTRARARCHIVO(nombreArchivo, extension, txtruta.Text) Then
                MessageBox.Show("Registro", "Registrado Correctamente", MessageBoxButtons.OK, MessageBoxIcon.Information)
                mostrar()
            Else
                MessageBox.Show("Registro", "No registrado", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If


        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub Archivos_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        mostrar()
    End Sub
    Sub mostrar()
        Try
            fun = New DArchivo
            DataGridView1.DataSource = fun.MOSTRARARCHIVO
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Sub obtenerNombreExtension()
        ''largo de la cadena 
        Dim largo As Integer
        largo = txtruta.Text.Length
        ''encontrar el punto para poder sacar la extension del archivo
        Dim tbus As String = "."
        Dim encon As Integer = txtruta.Text.IndexOf(tbus)

        ''saca el tamaño de la extension del archivo esta puede variar 
        Dim textencion As Integer
        textencion = largo - encon
        ''esto obtiene el valor de la extension del archivooo :D 
        extension = Mid(txtruta.Text, encon + 1, textencion)
        ''invierte la cadenaa para trabajar mejor 
        Dim cadinv As String = StrReverse(txtruta.Text)
        Dim simb As String = "\"
        Dim indicesimb As Integer = cadinv.IndexOf(simb)
        Dim nom As String = Mid(cadinv, 1, indicesimb)
        ''vuelve a invertir la cedena arreglandola 
        Dim nombre As String = StrReverse(nom)
        ''busca en que posicion esta el punto
        Dim punto As Integer = nombre.IndexOf(".")
        ''saca el tamaño de laextencion del archivo
        Dim tpunto As Integer = nombre.Length - punto
        'extrae el nombre del archivo sin la extension
        nombreArchivo = Mid(nombre, 1, nombre.Length - tpunto)
    End Sub
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Try

            fun = New DArchivo
            If fun.descargar(id, extension, txtcarpeta.Text, nom) Then
                MsgBox("Listo")
            Else
                MsgBox("No listo")
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Private Sub Button4_Click_1(sender As Object, e As EventArgs) Handles Button4.Click

        If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
            txtcarpeta.Text = FolderBrowserDialog1.SelectedPath

        End If
    End Sub

    Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        id = DataGridView1.SelectedCells.Item(0).Value
        nom = DataGridView1.SelectedCells.Item(1).Value
        MsgBox(id)
        MsgBox(nom)
    End Sub
End Class
    
asked by Jcastillo 28.03.2017 в 01:55
source

0 answers