C# System.IO命名空间常用的类

来源:互联网 发布:智慧旅游大数据平台 编辑:程序博客网 时间:2024/06/07 14:20


System.IO.Compression


GzipStream 常用于文件压缩解压缩


using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;


namespace OmegaConsoleLibary
{
    public class FileHelper
    {
        /// <summary>
        /// 文件压缩
        /// </summary>
        /// <param name="raw"></param>
        /// <returns></returns>
        public static byte[] CompressFile(byte[] raw)
        {

          using (MemoryStream memory = new MemoryStream())
            {
                using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
                {
                    gzip.Write(raw, 0, raw.Length);
                }
                return memory.ToArray();
            }

        }
        /// <summary>
        /// 文件解压缩
        /// </summary>
        /// <param name="raw"></param>
        /// <returns></returns>
        public static byte[] DeCompressFile(byte[] raw)
        {
            using (GZipStream gzipStream = new GZipStream(new MemoryStream(raw), CompressionMode.Decompress,true))
            {
                using (MemoryStream targetStream = new MemoryStream())
                {
                    gzipStream.CopyTo(targetStream);
                    return targetStream.ToArray();
                }
            }
        }

        /// <summary>
        /// 通过FileStream压缩文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="gzipPath"></param>
        public static void CompressFileByFileStream(string path,string gzipPath)
        {
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                using (FileStream gzipFile = File.Create(gzipPath))
                {
                    using (GZipStream gzip = new GZipStream(gzipFile, CompressionMode.Compress, true))
                    {
                        fs.CopyTo(gzip);
                    }
                }
            }
        }


        /// <summary>
        ///  通过FileStream解压缩文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="gzipPath"></param>
        public static void DeCompressFileByFileStream(string path, string gzipPath)
        {
            using (GZipStream gzipStream = new GZipStream(new FileStream(gzipPath,FileMode.Open), CompressionMode.Decompress, true))
            {
                using (FileStream targetStream = new FileStream(path,FileMode.OpenOrCreate))
                {
                    gzipStream.CopyTo(targetStream);
                }
            }
        }

  

    }
}




0 0
原创粉丝点击