10.3. (从网络上)下载文件(到本地):downloadFile


    //download file from url
    //makesure destination folder exist before call this function
    //input para example:
    //http://g-ecx.images-amazon.com/images/G/01/kindle/dp/2012/KC/KC-slate-01-lg._V401028090_.jpg
    //download\B007OZNZG0\KC-slate-01-lg._V401028090_.jpg
    public bool downloadFile(string fileUrl, string fullnameToStore, out string errStr, Action<int> funcUpdateProgress)
    {
        bool downloadOk = false;
        errStr = "未知错误!";

        if ((fileUrl == null) || (fileUrl == ""))
        {
            errStr = "URL地址为空!";
            return downloadOk;
        }

        if ((fullnameToStore == null) || (fullnameToStore == ""))
        {
            errStr = "文件保存路径为空!";
            return downloadOk;
        }

        //const int maxFileLen = 100 * 1024 * 1024; // 100M
        const int maxFileLen = 300 * 1024 * 1024; // 300M
        const int lessMaxFileLen = 100 * 1024 * 1024; // 100M
        Byte[] binDataBuf;
        try
        {
            binDataBuf = new Byte[maxFileLen];
        }
        catch (Exception ex)
        {
            //if no enough memory, then try alloc less
            binDataBuf = new Byte[lessMaxFileLen];
        }

        int respDataLen = getUrlRespStreamBytes(ref binDataBuf, fileUrl, null, null, 0, funcUpdateProgress);
        if (respDataLen < 0)
        {
            errStr = "无法下载文件数据!";
            return downloadOk;
        }

        if (saveBytesToFile(fullnameToStore, ref binDataBuf, respDataLen, out errStr))
        {
            downloadOk = true;
        }

        return downloadOk;
    }

    

例 10.3. downloadFile 的使用范例


        public void updateProgress(int percentage)
        {
            //pgbDownload.Value = percentage;
        }

        public void downloadPictures(string productUrl, string respHtml, out string[] picFullnameList)
        {
            //......
            
            string[] imageUrlList = amazonLib.extractProductImageList(respHtml);
            gLogger.Info("Extracted image url list:");
            if (imageUrlList != null)
            {
                picFullnameList = new string[imageUrlList.Length];
                for (int idx = 0; idx < imageUrlList.Length; idx++)
                {
                    string imageUrl = imageUrlList[idx];
                    gLogger.Info(String.Format("[{0}]={1}", idx, imageUrl));

                    string picFilename = crl.extractFilenameFromUrl(imageUrl);

                    string picFullFilename = Path.Combine(picFolderFullPath, picFilename);
                    string errorStr = "";
                    gLogger.Info(String.Format("Downloading {0} to {1}", imageUrl, picFullFilename));
                    crl.downloadFile(imageUrl, picFullFilename, out errorStr, updateProgress);