Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Общие вопросы по .NET и C# > Помогите разобраться с SharpZipLib


Автор: t77 29.7.2008, 11:35
Доброго времени суток.
Есть таблица в Базе данных.
В каждой строке таблицы есть поле("DATA_BIN") с зазипованным файлом HTML.
Файл зиповался следующим образом
Код

FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read);
if (fs.Length > 0x100000)// 1MB
{
MessageBox.Show("The size of a file exceeds admissible!", "Mail Generation", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Result = - 1;
return;
}
MemoryStream ms = new MemoryStream();
System.IO.Compression.GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
fs.Close();
gzip.Write(buffer, 0, buffer.Length);
gzip.Close();
byte[] compressed = ms.GetBuffer();

Дергаю по несколько строк из таблицы базы данных и заливаю их в DataTable(dtMail).
Затем прохожусь по dtMail, считываю зип значение поля из каждой строки и добавляю в созданный заранее зип файл.
Тоесть получается несколько файлов должны находиться в одном Зип файле.
Важно добавлять файлы в архив напрямую с потока, т.е без сохранения на диск !!!
Для начала пытаюсь раззиповать полученное значеное поля...
Код

//создаю зип файл
MemoryStream ms = new MemoryStream();
ZipFile ZF = new ZipFile(ms);
//переменная для хранения значения
string data;
//прохожусь по строкам DataTable
foreach (DataRow r in dtMail.Rows)
{
//1) считываю и раззиповываю зип значение поля-"DATA_BIN"
data = DecompressString(r["DATA_BIN"].ToString());
//2) добавляю в ZF файл,полученный результат
ZF.BeginUpdate();
ZF.Add(data);
}
ZF.CommitUpdate();
ZF.Close();
//метод раззипования
public static string DecompressString(string stringValue)
{
// Convert the string to a byte array.
byte[] byteArray = StringToBytes(stringValue);
int byteCount = 0;
// Use a memory stream as storage for the GZipStream.
using (MemoryStream memoryStream = new MemoryStream(byteArray))
{
// Decompress the data by writing through the GZipStream.
using (GZipStream gZipStream = new GZipStream(memoryStream,
CompressionMode.Decompress))
{
byteArray = new byte[byteArray.Length];
//Здесь получаю исключение
byteCount = gZipStream.Read(byteArray, 0, byteArray.Length);
}
}
// Return the byte array in string form.
return BytesToString(byteArray, byteCount);
}
private static byte[] StringToBytes(string stringValue)
{
int length = stringValue.Length;
byte[] resultBytes = new byte[length];
for (int i = 0; i < length; i++)
{
resultBytes[i] = (byte)stringValue[i];
}
return resultBytes;
}
private static string BytesToString(byte[] byteValues, int numberBytes)
{
char[] buffer = new char[numberBytes];
for (int i = 0; i < numberBytes; i++)
{
buffer[i] = (char)byteValues[i];
}
return new string(buffer);
}

В данном примере я получаю исключение
Код

The magic number in GZip header is not correct !

Что я делаю не так ?
Если кто знает более правильный путь решения данной задачи, прошу поделиться!
Помогите разобраться !
Заранее благодарю

Автор: t77 29.7.2008, 12:50
поставлю вопрос проще...
есть HTML документ, который был заархивирован
Код

FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read);
            if (fs.Length > 0x100000)// 1MB
            {
                MessageBox.Show("The size of a file exceeds admissible!", "Mail Generation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Result = - 1;
                return;
            }
            MemoryStream ms = new MemoryStream();
            System.IO.Compression.GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true);

            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, (int)fs.Length);
            fs.Close();

            gzip.Write(buffer, 0, buffer.Length);
            gzip.Close();

            byte[] compressed = ms.GetBuffer();

Вопрос- как теперь разархивировать его в оригинальный вид, с помощью SharpZipLib ??? smile 

Автор: neutrino 3.8.2008, 14:26
Вот пример того, как это делал я:
Код


        /// <summary>
        /// Creates new instance of CAP file handle. Binds internal components to handles.
        /// </summary>
        /// <param name="filename">Full path and file name of CAP file.</param>
        protected CAPFile(string filename)
        {
            FastZip fz = new FastZip();

            // Extract all CAP files from the CAP (JAR)
            string tempDir = System.Environment.GetEnvironmentVariable("temp");
            fz.ExtractZip(filename, tempDir, "");

            // Load all CAP files and add them to the dictionary
            ZipFile jarFile = new ZipFile(filename);
            foreach (ZipEntry compFile in jarFile)
            {
                if (compFile.IsFile)
                {
                    string fullName = tempDir + '\\' + compFile.Name.Replace('/', '\\');
                    Component component = Component.createComponent(fullName);
                    if (component != null)
                    {
                        string shortName = FileServices.extractFileNameFromPath(fullName);
                        capFiles.Add(shortName.ToLower(), component);
                    }
                }
            }
        }



Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)