c#之从服务器下载压缩包,并解压

项目的配置文件为了和服务器保持一致,每次打包时都从网上下载配置文件,由于下载的是zip压缩包,还需要解压,代码如下:

using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;
using System.Net;

public class CsvFilesDownloader
{
    const string RootUrl = "http://xxx-";       // csv 文件下载地址
    const string CSVDirAssetPath = "Assets/CSVConvertScripts/CSVFiles";                         // csv 文件保存目录

    #region Version

    public enum Version
    {
        Trunk, CBT3, CBT2, CBT1, TT, Daye, M4, M3, M2,
    }

    #endregion

    public static void Start(Version version)
    {
        string url = RootUrl + version;
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Post;

        var response = request.GetResponse();
        var stream = response.GetResponseStream();
        string saveDirPath = AssetBundleItem.GetFullPath(CSVDirAssetPath);

        Decompress(stream, saveDirPath);
    }

    // 需使用开源类库:ICSharpCode.SharpZipLib,可以网上下载
    static void Decompress(Stream src, string targetDirPath)
    {
        if (src == null)
            throw new ArgumentNullException("src");
        if (string.IsNullOrEmpty(targetDirPath))
            throw new ArgumentException("targetDirPath");

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

        using (ZipInputStream decompressor = new ZipInputStream(src))
        {
            ZipEntry entry;

            while ((entry = decompressor.GetNextEntry()) != null)
            {
                if (entry.IsDirectory)
                    continue;

                if (Path.GetExtension(entry.Name).ToLower() != ".csv")
                    continue;

                string fileName = Path.GetFileName(entry.Name);
                string path = Path.Combine(targetDirPath, fileName);
                byte[] data = new byte[2048];

                using (FileStream streamWriter = File.Create(path))
                {
                    int bytesRead;
                    while ((bytesRead = decompressor.Read(data, 0, data.Length)) > 0)
                        streamWriter.Write(data, 0, bytesRead);
                }
            }
        }
    }


}

  

转载请注明出处:http://www.cnblogs.com/jietian331/p/5019492.html

原文地址:https://www.cnblogs.com/jietian331/p/5019492.html