AnkitMittal
AnkitMittal

Reputation: 164

Save data from SQL Image field to pdf, msg, xls, txt file using C#

I have a table in DB with a field of type Image. The filed of type image stores data from attachments(uploaded from aspx application) which could be pdf, xls, msg, txt, etc. The table also has a field which stores the attachment name and extension type.

I have to save the attachments back to my file system for all the rows in that table.

I have tried the following but I do not have permissions to execute the below

DECLARE @ObjectToken INT
EXEC sp_OACreate 'ADODB.Stream', @ObjectToken OUTPUT
EXEC sp_OASetProperty @ObjectToken, 'Type', 1
EXEC sp_OAMethod @ObjectToken, 'Open'
EXEC sp_OAMethod @ObjectToken, 'Write', NULL, Content
EXEC sp_OAMethod @ObjectToken, 'SaveToFile', NULL, 'c:/file.msg', 2
EXEC sp_OAMethod @ObjectToken, 'Close'
EXEC sp_OADestroy @ObjectToken

Can anyone please let me know how to save all the attachments to the file system using C#. I am thinking of building a Windows Form App with a Save button.

Upvotes: 0

Views: 408

Answers (2)

Lucian
Lucian

Reputation: 3554

If you just want the files with quick and dirty method just use VBS with ADO:

Set BinaryStream = CreateObject("ADODB.Stream")
BinaryStream.Type = 1 ' = adTypeBinary
BinaryStream.Open

Dim UUIDARRAY() 
Redim UUIDARRAY(1000)
strConnection = "Driver={SQL Server};Server=<servername>;Database=<databasename>;Uid=<username>;Pwd=<userpasswor>;"
Set cn = CreateObject("ADODB.Connection")
cn.ConnectionString = strConnection    
cn.Open
If cn.State = 1 Then
    Set objrs=cn.execute( "Select <data> FROM <table> where <something>" )
    Dim error
    While not (objrs is nothing)
        set field = objrs.Fields(0)
        chunk_data = field.GetChunk(65536)
        BinaryStream.Write chunk_data

    Set objrs = objrs.NextRecordSet
    Wend
    cn.close
    BinaryStream.SaveToFile "binarydata.bin", 2 '= adSaveCreateOverWrite'
else
    wscript.echo  "Could not connect"
end if

Just use this script and replace all the <...> with relevant information.

Upvotes: 1

nvm-uli
nvm-uli

Reputation: 656

Execute this one on your SQL server (need sa rights)

sp_configure

‘show advanced options’, 1

GO

reconfigure

GO

Upvotes: 0

Related Questions