public void TooLong()
        {
            var zt       = new ZipNameTransform();
            var veryLong = new string('x', 65536);

            try
            {
                zt.TransformDirectory(veryLong);
                Assert.Fail("Expected an exception");
            }
            catch (PathTooLongException)
            {
            }
        }
        public void LengthBoundaryOk()
        {
            var    zt       = new ZipNameTransform();
            string veryLong = "c:\\" + new string('x', 65535);

            try
            {
                zt.TransformDirectory(veryLong);
            }
            catch
            {
                Assert.Fail("Expected no exception");
            }
        }
        public void Basic()
        {
            var t = new ZipNameTransform();

            TestFile(t, "abcdef", "abcdef");

            // This is ignored but could be converted to 'file3'
            TestFile(t, @"./file3", "./file3");

            // The following relative paths cant be handled and are ignored
            TestFile(t, @"../file3", "../file3");
            TestFile(t, @".../file3", ".../file3");

            // Trick filenames.
            TestFile(t, @".....file3", ".....file3");
        }
Exemplo n.º 4
0
 private async Task <BaseBasicProperties> GetBasicProperties()
 {
     using (ZipFile zipFile = await OpenZipFileAsync(FileAccessMode.Read))
     {
         if (zipFile == null)
         {
             return(new BaseBasicProperties());
         }
         zipFile.IsStreamOwner = true;
         var znt   = new ZipNameTransform(ContainerPath);
         var entry = zipFile.GetEntry(znt.TransformFile(Path));
         if (entry != null)
         {
             return(new ZipFolderBasicProperties(entry));
         }
         return(new BaseBasicProperties());
     }
 }
Exemplo n.º 5
0
        private StreamedFileDataRequestedHandler ZipDataStreamingHandler(string name)
        {
            return(async request =>
            {
                try
                {
                    // If called from here it fails with Access Denied?!
                    //var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath);
                    var hFile = await NativeFileOperationsHelper.OpenProtectedFileForRead(ContainerPath);

                    if (hFile.IsInvalid)
                    {
                        request.FailAndClose(StreamedFileFailureMode.CurrentlyUnavailable);
                        return;
                    }
                    using (ZipFile zipFile = new ZipFile(new FileStream(hFile, FileAccess.Read)))
                    {
                        zipFile.IsStreamOwner = true;
                        var znt = new ZipNameTransform(ContainerPath);
                        var entry = zipFile.GetEntry(znt.TransformFile(name));
                        if (entry != null)
                        {
                            using (var inStream = zipFile.GetInputStream(entry))
                                using (var outStream = request.AsStreamForWrite())
                                {
                                    await inStream.CopyToAsync(outStream);

                                    await outStream.FlushAsync();
                                }
                            request.Dispose();
                        }
                        else
                        {
                            request.FailAndClose(StreamedFileFailureMode.CurrentlyUnavailable);
                        }
                    }
                }
                catch
                {
                    request.FailAndClose(StreamedFileFailureMode.Failed);
                }
            });
        }
        public void Basic()
        {
            var t = new ZipNameTransform();

            TestFile(t, "abcdef", "abcdef");
            TestFile(t, @"\\uncpath\d1\file1", "file1");
            TestFile(t, @"C:\absolute\file2", "absolute/file2");

            // This is ignored but could be converted to 'file3'
            TestFile(t, @"./file3", "./file3");

            // The following relative paths cant be handled and are ignored
            TestFile(t, @"../file3", "../file3");
            TestFile(t, @".../file3", ".../file3");

            // Trick filenames.
            TestFile(t, @".....file3", ".....file3");
            TestFile(t, @"c::file", "_file");
        }
Exemplo n.º 7
0
        internal void Archive(Models.FileTransportInfo fileTransportInfo)
        {
            if (fileTransportInfo.SourceIsDirectory == false)
            {
                string             entryName = ZipEntry.CleanName(fileTransportInfo.DestinationFolderName + @"\" + fileTransportInfo.DestinationFileName);
                System.IO.FileInfo fileInfo  = new System.IO.FileInfo(fileTransportInfo.SourceFullNameWithBasePath);

                zipObject.Add(fileInfo.FullName, entryName);
            }
            else
            {
                string[]         files         = System.IO.Directory.GetFiles(fileTransportInfo.SourceFullNameWithBasePath, "*", System.IO.SearchOption.AllDirectories);
                ZipNameTransform nameTransform = new ZipNameTransform(fileTransportInfo.BasePath);
                foreach (string filename in files)
                {
                    string entryName = nameTransform.TransformFile(filename);
                    zipObject.Add(filename, entryName);
                }
            }
        }
Exemplo n.º 8
0
        private BaseBasicProperties GetBasicProperties()
        {
            var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath);

            if (hFile.IsInvalid)
            {
                return(new BaseBasicProperties());
            }
            using (ZipFile zipFile = new ZipFile(new FileStream(hFile, FileAccess.Read)))
            {
                zipFile.IsStreamOwner = true;
                var znt   = new ZipNameTransform(ContainerPath);
                var entry = zipFile.GetEntry(znt.TransformFile(Path));
                if (entry != null)
                {
                    return(new ZipFileBasicProperties(entry));
                }
                return(new BaseBasicProperties());
            }
        }
Exemplo n.º 9
0
        public override IAsyncOperation <IRandomAccessStreamWithContentType> OpenReadAsync()
        {
            return(AsyncInfo.Run <IRandomAccessStreamWithContentType>(async(cancellationToken) =>
            {
                if (Path == ContainerPath)
                {
                    if (BackingFile != null)
                    {
                        return await BackingFile.OpenReadAsync();
                    }
                    else
                    {
                        var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath);
                        if (hFile.IsInvalid)
                        {
                            return null;
                        }
                        return new StreamWithContentType(new FileStream(hFile, FileAccess.Read).AsRandomAccessStream());
                    }
                }

                ZipFile zipFile = await OpenZipFileAsync(FileAccessMode.Read);
                if (zipFile == null)
                {
                    return null;
                }
                zipFile.IsStreamOwner = true;
                var znt = new ZipNameTransform(ContainerPath);
                var entry = zipFile.GetEntry(znt.TransformFile(Path));
                if (entry != null)
                {
                    var nsStream = new NonSeekableRandomAccessStreamForRead(zipFile.GetInputStream(entry), (ulong)entry.Size)
                    {
                        DisposeCallback = () => zipFile.Close()
                    };
                    return new StreamWithContentType(nsStream);
                }
                return null;
            }));
        }
Exemplo n.º 10
0
        public override IAsyncOperation <IRandomAccessStream> OpenAsync(FileAccessMode accessMode)
        {
            return(AsyncInfo.Run <IRandomAccessStream>(async(cancellationToken) =>
            {
                bool rw = accessMode == FileAccessMode.ReadWrite;
                var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath, rw);
                if (hFile.IsInvalid)
                {
                    return null;
                }
                if (Path == ContainerPath)
                {
                    return new FileStream(hFile, FileAccess.Read).AsRandomAccessStream();
                }

                ZipFile zipFile = new ZipFile(new FileStream(hFile, rw ? FileAccess.ReadWrite : FileAccess.Read));
                zipFile.IsStreamOwner = true;
                var znt = new ZipNameTransform(ContainerPath);
                var entry = zipFile.GetEntry(znt.TransformFile(Path));
                if (!rw)
                {
                    if (entry != null)
                    {
                        return new NonSeekableRandomAccessStream(zipFile.GetInputStream(entry), (ulong)entry.Size)
                        {
                            DisposeCallback = () => zipFile.Close()
                        };
                    }
                }
                else
                {
                    return new RandomAccessStreamWithFlushCallback()
                    {
                        DisposeCallback = () => zipFile.Close(),
                        FlushCallback = WriteZipEntry(zipFile)
                    };
                }
                return null;
            }));
        }
Exemplo n.º 11
0
        public override IAsyncOperation <BaseStorageFile> CreateFileAsync(string desiredName, CreationCollisionOption options)
        {
            return(AsyncInfo.Run <BaseStorageFile>(async(cancellationToken) =>
            {
                using (ZipFile zipFile = await OpenZipFileAsync(FileAccessMode.ReadWrite))
                {
                    if (zipFile == null)
                    {
                        return null;
                    }
                    zipFile.IsStreamOwner = true;

                    var znt = new ZipNameTransform(ContainerPath);
                    var zipDesiredName = znt.TransformFile(System.IO.Path.Combine(Path, desiredName));
                    var entry = zipFile.GetEntry(zipDesiredName);

                    zipFile.BeginUpdate(new MemoryArchiveStorage(FileUpdateMode.Direct));
                    if (entry != null)
                    {
                        if (options != CreationCollisionOption.ReplaceExisting)
                        {
                            zipFile.AbortUpdate();
                            return null;
                        }
                        zipFile.Delete(entry);
                    }
                    zipFile.Add(new FileDataSource()
                    {
                        Stream = new MemoryStream()
                    }, zipDesiredName);
                    zipFile.CommitUpdate();

                    var wnt = new WindowsNameTransform(ContainerPath);
                    return new ZipStorageFile(wnt.TransformFile(zipDesiredName), ContainerPath)
                    {
                        BackingFile = BackingFile
                    };
                }
            }));
        }
Exemplo n.º 12
0
        public override IAsyncOperation <IInputStream> OpenSequentialReadAsync()
        {
            return(AsyncInfo.Run <IInputStream>(async(cancellationToken) =>
            {
                if (Path == ContainerPath)
                {
                    if (BackingFile != null)
                    {
                        return await BackingFile.OpenSequentialReadAsync();
                    }
                    else
                    {
                        var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath);
                        if (hFile.IsInvalid)
                        {
                            return null;
                        }
                        return new FileStream(hFile, FileAccess.Read).AsInputStream();
                    }
                }

                ZipFile zipFile = await OpenZipFileAsync(FileAccessMode.Read);
                if (zipFile == null)
                {
                    return null;
                }
                zipFile.IsStreamOwner = true;
                var znt = new ZipNameTransform(ContainerPath);
                var entry = zipFile.GetEntry(znt.TransformFile(Path));
                if (entry != null)
                {
                    return new InputStreamWithDisposeCallback(zipFile.GetInputStream(entry))
                    {
                        DisposeCallback = () => zipFile.Close()
                    };
                }
                return null;
            }));
        }
Exemplo n.º 13
0
        public override IAsyncOperation <BaseStorageFolder> CreateFolderAsync(string desiredName, CreationCollisionOption options)
        {
            return(AsyncInfo.Run <BaseStorageFolder>(async(cancellationToken) =>
            {
                var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath, true);
                if (hFile.IsInvalid)
                {
                    return null;
                }
                using (ZipFile zipFile = new ZipFile(new FileStream(hFile, FileAccess.ReadWrite)))
                {
                    zipFile.IsStreamOwner = true;

                    var znt = new ZipNameTransform(ContainerPath);
                    var zipDesiredName = znt.TransformDirectory(System.IO.Path.Combine(Path, desiredName));
                    var entry = zipFile.GetEntry(zipDesiredName);

                    zipFile.BeginUpdate(new MemoryArchiveStorage(FileUpdateMode.Direct));
                    if (entry != null)
                    {
                        if (options != CreationCollisionOption.ReplaceExisting)
                        {
                            zipFile.AbortUpdate();
                            return null;
                        }
                        zipFile.Delete(entry);
                    }
                    zipFile.AddDirectory(zipDesiredName);
                    zipFile.CommitUpdate();

                    var wnt = new WindowsNameTransform(ContainerPath);
                    return new ZipStorageFolder(wnt.TransformFile(zipDesiredName), ContainerPath)
                    {
                        ZipEncoding = ZipEncoding
                    };
                }
            }));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Create a zip archive sending output to the <paramref name="outputStream"/> passed.
        /// </summary>
        /// <param name="outputStream">The stream to write archive data to.</param>
        /// <param name="sourceDirectory">The directory to source files from.</param>
        /// <param name="recurse">True to recurse directories, false for no recursion.</param>
        /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param>
        /// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param>
        /// <remarks>The <paramref name="outputStream"/> is closed after creation.</remarks>
        public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter)
        {
            NameTransform    = new ZipNameTransform(sourceDirectory);
            sourceDirectory_ = sourceDirectory;

            using (outputStream_ = new ZipOutputStream(outputStream)) {
                outputStream_.SetLevel((int)CompressionLevel);

                if (password_ != null)
                {
                    outputStream_.Password = password_;
                }

                outputStream_.UseZip64 = UseZip64;
                var scanner = new FileSystemScanner(fileFilter, directoryFilter);
                scanner.ProcessFile += ProcessFile;
                if (this.CreateEmptyDirectories)
                {
                    scanner.ProcessDirectory += ProcessDirectory;
                }

                if (events_ != null)
                {
                    if (events_.FileFailure != null)
                    {
                        scanner.FileFailure += events_.FileFailure;
                    }

                    if (events_.DirectoryFailure != null)
                    {
                        scanner.DirectoryFailure += events_.DirectoryFailure;
                    }
                }

                scanner.Scan(sourceDirectory, recurse);
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// Initialise a new instance of <see cref="ZipEntryFactory"/> using the specified <see cref="TimeSetting"/>
 /// </summary>
 /// <param name="timeSetting">The <see cref="TimeSetting">time setting</see> to use when creating <see cref="ZipEntry">Zip entries</see>.</param>
 public IsolatedZipEntryFactory(TimeSetting timeSetting)
 {
     timeSetting_   = timeSetting;
     nameTransform_ = new ZipNameTransform();
 }
Exemplo n.º 16
0
        public override IAsyncOperation <IRandomAccessStream> OpenAsync(FileAccessMode accessMode)
        {
            return(AsyncInfo.Run <IRandomAccessStream>(async(cancellationToken) =>
            {
                bool rw = accessMode == FileAccessMode.ReadWrite;
                if (Path == ContainerPath)
                {
                    if (BackingFile != null)
                    {
                        return await BackingFile.OpenAsync(accessMode);
                    }
                    else
                    {
                        var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath, rw);
                        if (hFile.IsInvalid)
                        {
                            return null;
                        }
                        return new FileStream(hFile, rw ? FileAccess.ReadWrite : FileAccess.Read).AsRandomAccessStream();
                    }
                }

                if (!rw)
                {
                    ZipFile zipFile = await OpenZipFileAsync(accessMode);
                    if (zipFile == null)
                    {
                        return null;
                    }
                    zipFile.IsStreamOwner = true;
                    var znt = new ZipNameTransform(ContainerPath);
                    var entry = zipFile.GetEntry(znt.TransformFile(Path));
                    if (entry != null)
                    {
                        return new NonSeekableRandomAccessStreamForRead(zipFile.GetInputStream(entry), (ulong)entry.Size)
                        {
                            DisposeCallback = () => zipFile.Close()
                        };
                    }
                }
                else
                {
                    var znt = new ZipNameTransform(ContainerPath);
                    var zipDesiredName = znt.TransformFile(Path);

                    using (ZipFile zipFile = await OpenZipFileAsync(accessMode))
                    {
                        var entry = zipFile.GetEntry(zipDesiredName);
                        if (entry != null)
                        {
                            zipFile.BeginUpdate(new MemoryArchiveStorage(FileUpdateMode.Direct));
                            zipFile.Delete(entry);
                            zipFile.CommitUpdate();
                        }
                    }

                    if (BackingFile != null)
                    {
                        var zos = new ZipOutputStream((await BackingFile.OpenAsync(FileAccessMode.ReadWrite)).AsStream(), true);
                        await zos.PutNextEntryAsync(new ZipEntry(zipDesiredName));
                        return new NonSeekableRandomAccessStreamForWrite(zos);
                    }
                    else
                    {
                        var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath, true);
                        if (hFile.IsInvalid)
                        {
                            return null;
                        }
                        var zos = new ZipOutputStream(new FileStream(hFile, FileAccess.ReadWrite), true);
                        await zos.PutNextEntryAsync(new ZipEntry(zipDesiredName));
                        return new NonSeekableRandomAccessStreamForWrite(zos);
                    }
                }
                return null;
            }));
        }
Exemplo n.º 17
0
        /// <summary>
        /// SharpZipLib를 이용해 압축함. 간단 버전은 SharpZipLib의 FastZip 클래스 이용하면 되나 BeforeCompress 이벤트를 사용하기 위함.
        /// </summary>
        /// <param name="SearchPattern">
        /// The search string. For example, "System*" can be used to search for all directories that begin with the word "System".
        /// </param>
        public void CreateZip(string ZipFullPath, string SearchPattern, SearchOption SearchOption, string[] aSourceFolder, string Password)
        {
            using (ZipOutputStream OutputStream = new ZipOutputStream(File.Create(ZipFullPath)))
            {
                OutputStream.SetLevel(6);                 // 0 - store only to 9 - means best compression

                if (!string.IsNullOrEmpty(Password))
                {
                    OutputStream.Password = Password;
                }

                foreach (string SourceFolder in aSourceFolder)
                {
                    DirectoryInfo    di            = new DirectoryInfo(SourceFolder);
                    FileInfo[]       aFiles        = di.GetFiles(SearchPattern, SearchOption);
                    ZipNameTransform NameTransform = new ZipNameTransform(SourceFolder);

                    foreach (FileInfo file in aFiles)
                    {
                        string FullPathSrc = file.FullName;

                        string FolderNameInZip = NameTransform.TransformFile(file.FullName);

                        if (this.BeforeCompress != null)
                        {
                            CBeforeCompressEventArgs e = new CBeforeCompressEventArgs()
                            {
                                FullPathSrc     = FullPathSrc,
                                FolderNameInZip = FolderNameInZip
                            };
                            this.BeforeCompress(this, e);

                            if (e.Cancel)
                            {
                                continue;
                            }

                            if (!string.IsNullOrEmpty(e.NewFolderNameInZipIs))
                            {
                                FolderNameInZip = e.NewFolderNameInZipIs;
                            }
                        }

                        ZipEntry entry = new ZipEntry(FolderNameInZip);

                        entry.DateTime = file.LastWriteTime;

                        // set Size and the crc, because the information
                        // about the size and crc should be stored in the header
                        // if it is not set it is automatically written in the footer.
                        // (in this case size == crc == -1 in the header)
                        // Some ZIP programs have problems with zip files that don't store
                        // the size and crc in the header.
                        entry.Size = file.Length;

                        OutputStream.PutNextEntry(entry);

                        byte[] buffer = new byte[4096];
                        using (FileStream streamReader = File.OpenRead(FullPathSrc))
                        {
                            StreamUtils.Copy(streamReader, OutputStream, buffer);
                        }
                        OutputStream.CloseEntry();
                    }
                }

                OutputStream.Finish();
                OutputStream.Close();
            }
        }
Exemplo n.º 18
0
 /// <summary>
 /// Initialise a new instance of the <see cref="ZipEntryFactory"/> class.
 /// </summary>
 /// <remarks>A default <see cref="INameTransform"/>, and the LastWriteTime for files is used.</remarks>
 public IsolatedZipEntryFactory()
 {
     nameTransform_ = new ZipNameTransform();
 }
Exemplo n.º 19
0
 /// <summary>
 /// Initialise a new instance of <see cref="ZipEntryFactory"/> using the specified <see cref="DateTime"/>
 /// </summary>
 /// <param name="time">The time to set all <see cref="ZipEntry.DateTime"/> values to.</param>
 public IsolatedZipEntryFactory(DateTime time)
 {
     timeSetting_   = TimeSetting.Fixed;
     FixedDateTime  = time;
     nameTransform_ = new ZipNameTransform();
 }
            public static IFile New(IFile wrapFile, string name, string version, params string[] descriptorLines)
            {
                //var wrapFile = new InMemoryFile(name + "-" + version + ".wrap");
                using (var wrapStream = wrapFile.OpenWrite())
                using (var zipFile = new ZipOutputStream(wrapStream))
                {
                    var nameTransform = new ZipNameTransform();

                    zipFile.PutNextEntry(new ZipEntry(name + ".wrapdesc"));

                    var descriptorContent = descriptorLines.Any()
                                                    ? string.Join("\r\n", descriptorLines)
                                                    : " ";

                    zipFile.Write(Encoding.UTF8.GetBytes(descriptorContent));

                    var versionEntry = new ZipEntry("version");
                    zipFile.PutNextEntry(versionEntry);

                    var versionData = Encoding.UTF8.GetBytes(version);
                    zipFile.Write(versionData);
                    zipFile.Finish();
                }
                return wrapFile;
            }