SQL Server
SQL Server
Add Text from a StringBuilder to a ZIP Using AddSb
See more Zip Examples
This example demonstrates how to use the AddSb method to add text from a StringBuilder object as a file entry within a ZIP archive.
The text is converted to bytes using the specified character encoding before being stored in the ZIP archive.
This method is useful for dynamically generating text files entirely in memory without creating temporary files on disk.
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, 'stringBuilderData.zip'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @zip, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @zip
RETURN
END
-- Create a StringBuilder containing text data.
DECLARE @sb int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sb OUT
EXEC sp_OAMethod @sb, 'AppendLine', @success OUT, 'Line 1: Hello World!', 1
EXEC sp_OAMethod @sb, 'AppendLine', @success OUT, 'Line 2: This text came from a StringBuilder.', 1
-- Add the StringBuilder contents as a UTF-8 text file
-- stored in the ZIP archive as "docs/readme.txt".
EXEC sp_OAMethod @zip, 'AddSb', @success OUT, 'docs/readme.txt', @sb, 'utf-8'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @zip, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @zip
EXEC @hr = sp_OADestroy @sb
RETURN
END
-- Write the ZIP archive to disk and close it.
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
EXEC @hr = sp_OADestroy @sb
RETURN
END
PRINT 'ZIP archive created successfully.'
EXEC @hr = sp_OADestroy @zip
EXEC @hr = sp_OADestroy @sb
END
GO