SQL Server
SQL Server
Add Files to a ZIP Using AddFile
See more Zip Examples
This example demonstrates how to use the AddFile method to add files from the local filesystem to a ZIP archive.
The example adds two files:
- One file with its relative directory path preserved
- One file stored using only its filename
The AddFile method adds references to local filesystem files. The files are not actually read or compressed until a Write* method is called.
Chilkat SQL Server Downloads
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
DECLARE @hr int
-- Important: Do not use nvarchar(max). See the warning about using nvarchar(max).
DECLARE @sTmp0 nvarchar(4000)
DECLARE @success int
SELECT @success = 0
DECLARE @zip int
EXEC @hr = sp_OACreate 'Chilkat.Zip', @zip OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
EXEC sp_OAMethod @zip, 'NewZip', @success OUT, 'addFileExample.zip'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @zip, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @zip
RETURN
END
-- Add a file and preserve its relative directory structure
-- within the ZIP archive.
--
-- The following file:
-- c:/projects/app/docs/readme.txt
--
-- Will be stored in the ZIP as:
-- projects/app/docs/readme.txt
--
DECLARE @saveExtraPath int
SELECT @saveExtraPath = 1
EXEC sp_OAMethod @zip, 'AddFile', @success OUT, 'c:/projects/app/docs/readme.txt', @saveExtraPath
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @zip, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @zip
RETURN
END
-- Add a file using only the filename in the ZIP archive.
--
-- The following file:
-- c:/temp/logo.png
--
-- Will be stored in the ZIP as:
-- logo.png
--
SELECT @saveExtraPath = 0
EXEC sp_OAMethod @zip, 'AddFile', @success OUT, 'c:/temp/logo.png', @saveExtraPath
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @zip, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @zip
RETURN
END
-- Write the ZIP archive to disk and close it.
-- The source files are consumed at this time.
EXEC sp_OAMethod @zip, 'WriteZipAndClose', @success OUT
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @zip, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @zip
RETURN
END
PRINT 'ZIP archive created successfully.'
EXEC @hr = sp_OADestroy @zip
END
GO