C#下载远程文件并打包

C#下载远程文件并打包

using System;
using System.IO;
using System.IO.Compression;
using System.Net;

class Program
{
    static void Main()
    {
        string[] files = {

"http://www.xxx.com/xx1.xls",
"http://www.xxx.com/xx2.xls",
        };

        string output = "files.zip";

        using (FileStream newZipFile = new FileStream(output, FileMode.Create))
        {
            using (ZipArchive zipArchive = new ZipArchive(newZipFile, ZipArchiveMode.Create))
            {
                foreach (string fileURL in files)
                {
                    string fileName = Path.GetFileName(fileURL);
                    byte[] fileBytes = DownloadFile(fileURL);
                    if (fileBytes != null)
                    {
                        ZipArchiveEntry zipEntry = zipArchive.CreateEntry(fileName, CompressionLevel.Fastest);
                        using (Stream entryStream = zipEntry.Open())
                        {
                            entryStream.Write(fileBytes, 0, fileBytes.Length);
                        }
                    }
                }
            }
        }

        Console.WriteLine("Zipped File: " + output);
    }

    static byte[] DownloadFile(string url)
    {
        using (WebClient client = new WebClient())
        {
            try
            {
                return client.DownloadData(url);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
    }
}

  

posted @ 2023-11-21 13:48  iDEAAM  阅读(112)  评论(0编辑  收藏  举报