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;
            }
        }
    }
}

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章