Web developers wiki ASP.NET Sitecore Sharepoint Kentico by Evident Interactive

Compressing memory stream using GZipStream

Modified: 2010/11/22 10:38 by jim - Categorized as: ASP.NET, Csharp, Security
Case: send files stored in an SQL database to an FTP server. The tricky part was we did not want to use the file system to temporarily store the files so we had to keep the file in memory all the time. Problems we encountered: broken files on the ftp server. Solution: creating a GZipStream with an overloaded constructor so the underlying stream does not close when the zipstream is closed.

string ftpServerIP = ConfigurationManager.AppSettings["FtpPath"].ToString();
string ftpUserID = ConfigurationManager.AppSettings["FtpUser"].ToString();
string ftpPassword = ConfigurationManager.AppSettings["FtpPassword"].ToString();

// name of database document
FileInfo fileInf = new FileInfo(docName);
FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));

// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
// byteArray contains the database document (varbinary(max))
reqFTP.ContentLength = byteArray.Length;
reqFTP.UsePassive = true;
// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;

MemoryStream memStream = new MemoryStream(byteArray);
MemoryStream zippedStream = new MemoryStream();

// normally when you close a stream, the underlying stream is closed as well. GZipStream
// has an overload to leave the underlying stream open
GZipStream gzStream = new GZipStream(zippedStream, CompressionMode.Compress, true);
// copy to gzStream so zippedStream now contains zipped bytes.
// now close the GZip stream
// dont forget to reset the zipped stream
zippedStream.Position = 0;

Stream strm = reqFTP.GetRequestStream();
contentLen = zippedStream.Read(buff, 0, buffLength);
while (contentLen != 0)
// Write Content from the file stream to the FTP Upload Stream
	strm.Write(buff, 0, contentLen);
	contentLen = zippedStream.Read(buff, 0, buffLength);
// Close the file stream and the Request Stream

 © Evident Interactive BV