コード例 #1
0
 public override IAsyncAction CopyAndReplaceAsync(IStorageFile fileToReplace)
 {
     return(AsyncInfo.Run(async(cancellationToken) =>
     {
         var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath);
         if (hFile.IsInvalid)
         {
             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(Path));
             if (entry != null)
             {
                 using var hDestFile = fileToReplace.CreateSafeFileHandle(FileAccess.ReadWrite);
                 using (var inStream = zipFile.GetInputStream(entry))
                     using (var outStream = new FileStream(hDestFile, FileAccess.Write))
                     {
                         await inStream.CopyToAsync(outStream);
                         await outStream.FlushAsync();
                     }
             }
         }
     }));
 }
コード例 #2
0
        public override IAsyncOperation <IRandomAccessStreamWithContentType> OpenReadAsync()
        {
            return(AsyncInfo.Run <IRandomAccessStreamWithContentType>(async(cancellationToken) =>
            {
                var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath);
                if (hFile.IsInvalid)
                {
                    return null;
                }
                if (Path == ContainerPath)
                {
                    return new StreamWithContentType(new FileStream(hFile, FileAccess.Read).AsRandomAccessStream());
                }

                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)
                {
                    var nsStream = new NonSeekableRandomAccessStream(zipFile.GetInputStream(entry), (ulong)entry.Size)
                    {
                        DisposeCallback = () => zipFile.Close()
                    };
                    return new StreamWithContentType(nsStream);
                }
                return null;
            }));
        }
コード例 #3
0
        public override IAsyncOperation <IInputStream> OpenSequentialReadAsync()
        {
            return(AsyncInfo.Run <IInputStream>(async(cancellationToken) =>
            {
                var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath);
                if (hFile.IsInvalid)
                {
                    return null;
                }
                if (Path == ContainerPath)
                {
                    return new FileStream(hFile, FileAccess.Read).AsInputStream();
                }

                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 InputStreamWithDisposeCallback(zipFile.GetInputStream(entry))
                    {
                        DisposeCallback = () => zipFile.Close()
                    };
                }
                return null;
            }));
        }
コード例 #4
0
        private Func <IRandomAccessStream, IAsyncOperation <bool> > WriteZipEntry(ZipFile zipFile)
        {
            return((stream) => AsyncInfo.Run((cancellationToken) => Task.Run(() =>
            {
                var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath, true);
                if (hFile.IsInvalid)
                {
                    return true;
                }
                try
                {
                    var znt = new ZipNameTransform(ContainerPath);
                    var zipDesiredName = znt.TransformFile(Path);
                    var entry = zipFile.GetEntry(zipDesiredName);

                    zipFile.BeginUpdate(new MemoryArchiveStorage(FileUpdateMode.Direct));
                    if (entry != null)
                    {
                        zipFile.Delete(entry);
                    }
                    zipFile.Add(new StreamDataSource(stream), zipDesiredName);
                    zipFile.CommitUpdate();
                }
                catch (Exception ex)
                {
                    App.Logger.Warn(ex, "Error writing zip file");
                }
                return true;
            })));
        }
コード例 #5
0
 public override IAsyncOperation <BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option)
 {
     return(AsyncInfo.Run <BaseStorageFile>(async(cancellationToken) =>
     {
         var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath);
         if (hFile.IsInvalid)
         {
             return null;
         }
         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)
             {
                 var destFolder = destinationFolder.AsBaseStorageFolder();
                 var destFile = await destFolder.CreateFileAsync(desiredNewName, option.Convert());
                 using (var inStream = zipFile.GetInputStream(entry))
                     using (var outStream = await destFile.OpenStreamForWriteAsync())
                     {
                         await inStream.CopyToAsync(outStream);
                         await outStream.FlushAsync();
                     }
                 return destFile;
             }
             return null;
         }
     }));
 }
コード例 #6
0
        public void NameTransforms_Posix()
        {
            INameTransform t = new ZipNameTransform(@"/Slippery");

            Assert.AreEqual("Pongo/Directory/", t.TransformDirectory(@"/Slippery\Pongo\Directory"), "Value should be trimmed and converted");
            Assert.AreEqual("PoNgo/Directory/", t.TransformDirectory(@"/slipperY\PoNgo\Directory"), "Trimming should be case insensitive");
            Assert.AreEqual("slippery/Pongo/Directory/", t.TransformDirectory(@"/slippery/slippery/Pongo/Directory"), "Trimming should account for root");

            Assert.AreEqual("Pongo/File", t.TransformFile(@"/Slippery/Pongo/File"), "Value should be trimmed and converted");
        }
コード例 #7
0
        public void NameTransforms()
        {
            INameTransform t = new ZipNameTransform(@"C:\Slippery");

            Assert.AreEqual("Pongo/Directory/", t.TransformDirectory(@"C:\Slippery\Pongo\Directory"), "Value should be trimmed and converted");
            Assert.AreEqual("PoNgo/Directory/", t.TransformDirectory(@"c:\slipperY\PoNgo\Directory"), "Trimming should be case insensitive");
            Assert.AreEqual("slippery/Pongo/Directory/", t.TransformDirectory(@"d:\slippery\Pongo\Directory"), "Trimming should be case insensitive");

            Assert.AreEqual("Pongo/File", t.TransformFile(@"C:\Slippery\Pongo\File"), "Value should be trimmed and converted");
        }
コード例 #8
0
        public void PathalogicalNames()
        {
            string badName = ".*:\\zy3$";

            Assert.IsFalse(ZipNameTransform.IsValidName(badName));

            var    t      = new ZipNameTransform();
            string result = t.TransformFile(badName);

            Assert.IsTrue(ZipNameTransform.IsValidName(result));
        }
コード例 #9
0
        public override void AddFile(string directory, string file, string content)
        {
            if (this.IsOpen)
            {
                if (content == null)
                {
                    content = string.Empty;
                }
                file = Path.Combine(directory, file);
                file = _zipNameTransform.TransformFile(file);
                ZipEntry entry = new ZipEntry(file);
                System.Diagnostics.Trace.WriteLine("Adding file: " + file);

                UTF8Encoding utf8Encoding = new UTF8Encoding();
                byte[]       buffer       = utf8Encoding.GetBytes(content);
                entry.DateTime = DateTime.Now;
                entry.Size     = buffer.Length;
                _zipOutput.PutNextEntry(entry);
                _zipOutput.Write(buffer, 0, buffer.Length);
                entry.Size = buffer.Length;
            }
        }
コード例 #10
0
ファイル: ZipStorageFolder.cs プロジェクト: lyrl/files-uwp
 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());
     }
 }
コード例 #11
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);
                }
            });
        }
コード例 #12
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);
                }
            }
        }
コード例 #13
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());
            }
        }
コード例 #14
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;
            }));
        }
コード例 #15
0
ファイル: ZipStorageFolder.cs プロジェクト: lyrl/files-uwp
        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
                    };
                }
            }));
        }
コード例 #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;
            }));
        }
コード例 #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();
            }
        }