
.NET · April 8, 2004
SharpZipLib Zipped XML File Upload with In Memory Unzip and SQL Import
SharpZipLib Zipped XML File Upload with In Memory Unzip and SQL Import
SharpZipLib follow up: Today I was able to finally get a File Upload and In Memory Unzip working, without writing out to a file. (This way, I could upload a Zipped XML file via ASP.Net and Import it into the database without ever having to write to the file system. Here's the functions that finally worked:
```
private string Unzip()
{
int length = (int)UpdateFile.PostedFile.InputStream.Length;
byte[] bytInputData = new byte[length];
UpdateFile.PostedFile.InputStream.Read(bytInputData,0,length);
//bytInputData = DeCompress(bytInputData);
bytInputData = UnzipBytes(bytInputData);
return Encoding.ASCII.GetString(bytInputData);
}
private byte[] UnzipBytes(byte[] bytesToDecompress)
{
ZipEntry objZipEntry;
ZipInputStream objZipInputStream = new ZipInputStream(new MemoryStream(bytesToDecompress));
MemoryStream outStream = new MemoryStream();
while ((objZipEntry = objZipInputStream.GetNextEntry()) != null )
{
if ( Path.GetFileName(objZipEntry.Name) != "" )
{
int intSize = 2048;
byte[] arrData = new byte[2048];
intSize = objZipInputStream.Read(arrData, 0, arrData.Length);
while ( intSize > 0 )
{
outStream.Write(arrData, 0, intSize);
intSize = objZipInputStream.Read(arrData, 0, arrData.Length);
}
}
}
objZipInputStream.Close();
byte[] outArr = outStream.ToArray();
outStream.Close();
return outArr;
}
```
At first it wasn't in my real application, it was inside of my test app, and after experimentation I found that you can not read the PostedFile into a byte array more than once. I was getting an "invalid header0" type of message, even though the byte array was the same size each time. Strange.
# Comments
Chanrith Peth said on October 16, 2007 3:04 PM:
Thanks for the write up, this was really helpful. Saved me hours!