Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ICSharpCode.SharpZipLib.Zip.FastZip not zipping files having special characters in their file names

I am using ICSharpCode.SharpZipLib.Zip.FastZip to zip files but I'm stuck on a problem:

When I try to zip a file with special characters in its file name, it does not work. It works when there are no special characters in the file name.

like image 690
BreakHead Avatar asked Nov 22 '10 13:11

BreakHead


3 Answers

I think you cannot use FastZip. You need to iterate the files and add the entries yourself specifying:

entry.IsUnicodeText = true;

To tell SharpZipLib the entry is unicode.

string[] filenames = Directory.GetFiles(sTargetFolderPath);

// Zip up the files - From SharpZipLib Demo Code
using (ZipOutputStream s = new
    ZipOutputStream(File.Create("MyZipFile.zip")))
{
    s.SetLevel(9); // 0-9, 9 being the highest compression

    byte[] buffer = new byte[4096];

    foreach (string file in filenames)
    {
         ZipEntry entry = new ZipEntry(Path.GetFileName(file));

         entry.DateTime = DateTime.Now;
         entry.IsUnicodeText = true;
         s.PutNextEntry(entry);

         using (FileStream fs = File.OpenRead(file))
         {
             int sourceBytes;
             do
             {
                 sourceBytes = fs.Read(buffer, 0, buffer.Length);

                 s.Write(buffer, 0, sourceBytes);

             } while (sourceBytes > 0);
         }
    }
    s.Finish();
    s.Close();
 }
like image 92
Paaland Avatar answered Sep 18 '22 17:09

Paaland


You can continue using FastZip if you would like, but you need to give it a ZipEntryFactory that creates ZipEntrys with IsUnicodeText = true.

var zfe = new ZipEntryFactory { IsUnicodeText = true };
var fz = new FastZip { EntryFactory = zfe };
fz.CreateZip("out.zip", "C:\in", true, null);
like image 28
blachniet Avatar answered Sep 18 '22 17:09

blachniet


You have to download and compile the latest version of SharpZipLib library so you can use

entry.IsUnicodeText = true;

here is your snippet (slightly modified):

FileInfo file = new FileInfo("input.ext");
using(var sw = new FileStream("output.zip", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
    using(var zipStream = new ZipOutputStream(sw))
    {
        var entry = new ZipEntry(file.Name);
        entry.IsUnicodeText = true;
        zipStream.PutNextEntry(entry);

        using (var reader = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
            {
                byte[] actual = new byte[bytesRead];
                Buffer.BlockCopy(buffer, 0, actual, 0, bytesRead);
                zipStream.Write(actual, 0, actual.Length);
            }
        }
    }
}
like image 32
Salaros Avatar answered Sep 20 '22 17:09

Salaros