Link to home
Start Free TrialLog in
Avatar of DavidGreenfield
DavidGreenfieldFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Importing and Exporting files to an SQL Server Database from VB.Net

Hi there

I am storing in a database files (*.pdf, *.doc, *.bmp etc) as below

                Dim fs As New System.IO.FileStream(s(i), IO.FileMode.Open, IO.FileAccess.Read)
                Dim bytes() As Byte
                ReDim bytes(fs.Length)
                fs.Read(bytes, 0, fs.Length)
...................................
                cmd.Parameters.Add("file", SqlDbType.Image).Value = bytes

I now want to get the file back.  For this I am doing:

            file = System.IO.Path.GetFileName(SaveFileDialog1.FileName)
            file_path = System.IO.Path.GetDirectoryName(SaveFileDialog1.FileName)
.................
            Dim fs As New System.IO.FileStream(SaveFileDialog1.FileName, IO.FileMode.CreateNew, IO.FileAccess.Write)
            fs.Write(dt.Rows(0).Item("file"), 0, Len(dt.Rows(0).Item("filename")))
            fs.Close()

It is creating a file of the right name etc, but the file cannot be loaded correctly.

What am I doing wrong? Or is there a better way (and if so how).

Many thanks!!

ASKER CERTIFIED SOLUTION
Avatar of ullfindsmit
ullfindsmit
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DavidGreenfield

ASKER

Thanks Smit, I didn't notice using the wrong variable!

However on changing it, I am still getting the same problem - i.e. the file being created won't load, i.e. it appears corrupted to the application opening it.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Got it finally the magic code is:

fs.Write(CType(dt.Rows(0).Item("file"), Byte()), 0, CType(dt.Rows(0).Item("file"), Byte()).GetLength(0))

Thanks to you both for pointing out my errors!