VS2010 C# 壓縮單一檔案(使用.NET 4 內建元件)

VS2010 C# 壓縮單一檔案(使用.NET 4 內建元件)

VS2010 C# 壓縮單一檔案(使用.NET 4 內建元件)


 

資料來源: https://msdn.microsoft.com/zh-tw/library/ms404280(v=vs.100).aspx

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

//https://msdn.microsoft.com/zh-tw/library/ms404280(v=vs.100).aspx

using System.IO;

using System.IO.Compression;

 

namespace Console_CS_zip

{

    class Program

    {

        public
static void
Compress(FileInfo fi)

        {

            // Get
the stream of the source file.

            using
(FileStream inFile = fi.OpenRead())

            {

                //
Prevent compressing hidden and

                //
already compressed files.

                if
((File.GetAttributes(fi.FullName)

                    &
FileAttributes.Hidden)

                    != FileAttributes.Hidden
& fi.Extension !=
“.gz”)

                {

                    //
Create the compressed file.

                    using
(FileStream outFile =

                               
File.Create(fi.FullName +
“.gz”))

                    {

                        using (GZipStream Compress =

                            new GZipStream(outFile,

                           
CompressionMode.Compress))

                        {

                            // Copy the source file into

                            // the compression stream.

                           
inFile.CopyTo(Compress);

 

                           
Console.WriteLine(
“Compressed {0}
from {1} to {2} bytes.”
,

                                fi.Name,
fi.Length.ToString(), outFile.Length.ToString());

                        }

                    }

                }

            }

        }

        static
void Pause()

        {

            Console.Write(“Press any key to continue . . . “);

            Console.ReadKey(true);

        }

        static
void Main(string[]
args)

        {

            // Path
to directory of files to compress and decompress.

            string
dirpath = @”C:\Users\RD\Desktop\Release”;

 

            DirectoryInfo di = new DirectoryInfo(dirpath);

 

            //
Compress the directory’s files.

            foreach
(FileInfo fi in di.GetFiles())

            {

                Compress(fi);

 

            }

            Pause();

            /*

            // Decompress all *.gz
files in the directory.

            foreach (FileInfo fi
in di.GetFiles(“*.gz”))

            {

                Decompress(fi);

 

            }

            */

        }

    }

}

 

 

 


 


發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *