想到要如何壓縮資料檔案就查了一下

看了一堆高手的順便整理一下GZipStream程式

第一種方式:也是最簡單的方式慢慢延伸就是自己要的了

//壓縮  
protected void Compress_Click1(object sender, EventArgs e)
{
  //己經有確定要壓縮的檔案
  FileStream sourceFile = File.OpenRead(@"C:\sample.xml");
  //壓縮後的檔案名稱
  FileStream destFile = File.Create(@"C:\sample.gz");  
  //開始
  GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress, true);
  try
    {
      int theByte = sourceFile.ReadByte();
      while (theByte != -1)
        {
          compStream.WriteByte((byte)theByte);
          theByte = sourceFile.ReadByte();
        }           
    }
  finally
    {
      compStream.Flush();
      compStream.Dispose();
      sourceFile.Flush();
      sourceFile.Dispose();
      destFile.Flush();
      destFile.Dispose();
    }
}

//解壓縮
protected void Decompress_Click(object sender, EventArgs e)
{       
  //被壓縮後的檔案
  FileStream sourceFile = File.OpenRead(@"C:\sample.gz");
  //解壓縮後的檔案
  FileStream destFile = File.Create(@"C:\Unsample.xml");

  //開始
  GZipStream compStream = new GZipStream(sourceFile, CompressionMode.Decompress, true);
  try
    {
      int theByte = compStream.ReadByte();
      while (theByte != -1)
        {                
          destFile.WriteByte((byte)theByte);
          theByte = compStream.ReadByte();
        }          
    }
  finally
    {
      compStream.Flush();
      compStream.Dispose();
      sourceFile.Flush();
      sourceFile.Dispose();
      destFile.Flush();
      destFile.Dispose();
    }
}

第二種方式:別人寫的小改了一些些....比較完整方便

protected void Compress_Click(object sender, EventArgs e)
{
    string strPath, strReadTextContent;
    strPath = Server.MapPath("TestFile");
    strReadTextContent = "我是測試資料我是測試資料我是測試資料";

    if (!Directory.Exists(strPath))
       Directory.CreateDirectory(strPath);

        //讀取檔案內容
        //string strReadTextContent = File.ReadAllText(Server.MapPath("TestFile/TextFile.txt"));

    CompressToFile(Server.MapPath("TestFile/TextFile.gz"), strReadTextContent);
}

public void CompressToFile(string strCompressFileName, string strFileContent)
{
        try
        {
            //建立一個暫存的檔案
            string tempFilePath = Path.GetTempFileName();

            byte[] b;

            //將指定的資料寫入暫存檔案中
            File.WriteAllText(tempFilePath, strFileContent, System.Text.Encoding.UTF8);

            //開啟建立的暫存檔將資料全部讀取
            using (FileStream f_ReadTempFileContent = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read))
            {
                b = new byte[f_ReadTempFileContent.Length];
                f_ReadTempFileContent.Read(b, 0, (int)f_ReadTempFileContent.Length);
            }

            //建立strCompressFileName檔案
            using (FileStream f_CompressFileName = new FileStream(strCompressFileName, FileMode.Create))
            {
                //開始進行壓縮
                using (GZipStream zip = new GZipStream(f_CompressFileName, CompressionMode.Compress, false))
                {
                    zip.Write(b, 0, b.Length);
                }
            }
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "alert('Error:" + ex.ToString() + "');", true);
        }

        Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "alert('完成壓縮');", true);
}

public void DecompressToFile(string strCompressFileName, string strDecompressFileName)
{
        int bufferSize = 4096;
        byte[] buffer = new byte[bufferSize];

        try
        {
            //讀取壓縮的strCompressFileName檔案
            using (FileStream fs_CompressFile = new FileStream(strCompressFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                //建立一個解壓縮後的檔案路徑與名稱
                using (FileStream fs_DecompressFile = new FileStream(strDecompressFileName, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    //解壓縮strCompressFileName的檔案
                    using (GZipStream zip = new GZipStream(fs_CompressFile, CompressionMode.Decompress, true))
                    {
                        //讀取strCompressFileName中的壓縮檔內容,並寫入新建立的檔案中                             
                        int n = 0;
                        while ((n = zip.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            fs_DecompressFile.Write(buffer, 0, n);
                        }
                    }
                }
            }

            //刪除壓縮檔
            File.Delete(strCompressFileName);
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "alert('Error:" + ex.ToString() + "');", true);
        }

        Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "alert('完成解壓縮');", true);
}

第三種方式:也是人家寫的有可用在WebService不過我只是拿來參考小小小改寫了一下....

protected void btnCompress1_Click(object sender, EventArgs e)
{
        try
        {
            byte[] da = ZipData();

            MemoryStream input = new MemoryStream();
            input.Write(da, 0, da.Length);
            input.Position = 0;

            GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true);

            MemoryStream output = new MemoryStream();
            byte[] buff = new byte[4096];
            int read = -1;
            read = gzip.Read(buff, 0, buff.Length);
            while (read > 0)
            {
                output.Write(buff, 0, read);
                read = gzip.Read(buff, 0, buff.Length);
            }
            gzip.Close();
            byte[] rebytes = output.ToArray();
            output.Close();
            input.Close();

            MemoryStream ms = new MemoryStream(rebytes);
            DataSet ds = new DataSet();
            ds.ReadXml(ms);

            GridView1.DataSource = LoadData();
            GridView1.DataBind();

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

    }

    public byte[] ZipData()
    {
        DataSet ds = LoadData().Copy();

        MemoryStream ms = new MemoryStream();
        ds.WriteXml(ms);

        Byte[] bytes = ms.ToArray();
        int lenByte = bytes.Length;

        MemoryStream compMs = new MemoryStream();
        GZipStream compStream = new GZipStream(compMs, CompressionMode.Compress, true);
        compStream.Write(bytes, 0, lenByte);
        compStream.Close();
        ms.Close();
        compMs.Close();
        byte[] zipData = compMs.ToArray();
        return zipData;
    }

    protected void btnCompress2_Click(object sender, EventArgs e)
    {
        try
        {
            byte[] da = ZipDataSer();

            MemoryStream input = new MemoryStream();
            input.Write(da, 0, da.Length);
            input.Position = 0;
            GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true);

            MemoryStream output = new MemoryStream();
            byte[] buff = new byte[4096];
            int read = -1;
            read = gzip.Read(buff, 0, buff.Length);
            while (read > 0)
            {
                output.Write(buff, 0, read);
                read = gzip.Read(buff, 0, buff.Length);
            }
            gzip.Close();
            byte[] rebytes = output.ToArray();
            output.Close();
            input.Close();

            MemoryStream ms = new MemoryStream(rebytes);
            BinaryFormatter bf = new BinaryFormatter();
            object obj = bf.Deserialize(ms);
            DataSet ds = (DataSet)obj;

            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

    }

    public byte[] ZipDataSer()
    {
        DataSet ds = LoadData().Copy();
        ds.RemotingFormat = SerializationFormat.Binary;
        BinaryFormatter ser = new BinaryFormatter();
        MemoryStream unMS = new MemoryStream();
        ser.Serialize(unMS, ds);

        byte[] bytes = unMS.ToArray();
        int lenbyte = bytes.Length;

        MemoryStream compMs = new MemoryStream();
        GZipStream compStream = new GZipStream(compMs, CompressionMode.Compress, true);
        compStream.Write(bytes, 0, lenbyte);

        compStream.Close();
        unMS.Close();
        compMs.Close();
        byte[] zipData = compMs.ToArray();
        return zipData;
    }

    private DataSet LoadData()
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable("testCompress");
        dt.Columns.Add("序號", typeof(int));
        dt.Columns.Add("價格", typeof(string));
        dt.Columns.Add("編碼", typeof(string));
        dt.Columns.Add("日期", typeof(DateTime));

        Random rm = new Random();
        for (int i = 0; i < 100; i++)
        {
            DataRow dw = dt.NewRow();
            dw["序號"] = i;
            dw["價格"] = rm.Next(1, 1000);
            dw["編碼"] = Guid.NewGuid().ToString();
            dw["日期"] = DateTime.Now.ToString();
            dt.Rows.Add(dw);
        }

        ds.Tables.Add(dt);
        ds.AcceptChanges();
        return ds;
}

第四種方式:

//壓縮
public void GZipCompressString()
{ 
  string rawString = "這是測試壓縮用資料";
  byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString.ToString());
  byte[] zippedData = Compress(rawData);
  Response.Write(Convert.ToBase64String(zippedData)).ToString();
}

private static byte[] Compress(byte[] rawData)
{
    MemoryStream ms = new MemoryStream();
    GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
    compressedzipStream.Write(rawData, 0, rawData.Length);
    compressedzipStream.Close();
    return ms.ToArray();
}

//解壓縮
public void GZipDecompressString(string zippedString)
{
    if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0)    
        Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "alert('字串是空的!!');", true);    
    else
    {
        byte[] zippedData = Convert.FromBase64String(zippedString.ToString());
        Response.Write(System.Text.Encoding.UTF8.GetString(Decompress(zippedData)));
    }
}

private static byte[] Decompress(byte[] zippedData)
{
    MemoryStream ms = new MemoryStream(zippedData);
    GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress);
    MemoryStream outBuffer = new MemoryStream();
    byte[] block = new byte[1024];
    while (true)
    {
        int bytesRead = compressedzipStream.Read(block, 0, block.Length);
        if (bytesRead <= 0)
            break;
        else
            outBuffer.Write(block, 0, bytesRead);
    }
    compressedzipStream.Close();
    return outBuffer.ToArray();
}

以上參考自:

http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx

http://www.dotblogs.com.tw/jeff-yeh/archive/2008/04/16/2932.aspx

http://www.dotblogs.com.tw/dc690216/archive/2010/02/07/13515.aspx

arrow
arrow
    全站熱搜

    鴨爸 發表在 痞客邦 留言(1) 人氣()