C# zip/unzip with DotNet framework 4.5

zyip發表於2014-04-17

 

add reference System.IO.Compression.FileSystem

    public class ZipHelper
    {
        public static string UnZip(string inputFile)
        {
            string outDir = System.Environment.CurrentDirectory + "\\executor\\";
            if (UnZip(inputFile, outDir))
                return outDir;
            else
                return "";
        }


        public static bool UnZip(string inputFile, string outputDir)
        {
            bool result = false;
            try
            {
                //ZipFile.ExtractToDirectory(inputFile, outputDir);
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(inputFile)))
                {

                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {

                        Console.WriteLine(theEntry.Name);

                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        //string directoryName = outputDir;
                        string fileName = Path.GetFileName(theEntry.Name);

                        // create directory
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(directoryName);
                        }

                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(theEntry.Name))
                            {

                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                        streamWriter.Close();
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                result = true;
            }
            catch
            {
            }
            return result;
        }

        //public static bool UnZip(string inputFile, string outputDir)
        //{
        //    bool result = false;
        //    try
        //    {
        //        ZipFile.ExtractToDirectory(inputFile, outputDir);
        //        result = true;
        //    }
        //    catch
        //    {
        //    }
        //    return result;
        //}
    }

 

 

相關文章