天天看點

winform 下載下傳網絡資源

調用

//網絡位址                      檔案的名字                存放本地路徑
DownLoadFile.HttpDownload(@"http://39.127.0.1:8092/" + readerppp.GetString(2), "./img/" + readerppp.GetString(2));
           

工具

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;


namespace TextWinform1
{
    class DownLoadFile
    {
        /// <summary>
        /// 專門的下載下傳檔案類
        /// </summary>
      
            /// <summary>
            /// http下載下傳檔案
            /// </summary>
            /// <param name="url"></param>
            /// <param name="path"></param>
            /// </summary>
            /// <param name="url">下載下傳檔案位址</param>
            /// <param name="path">檔案存放位址,包含檔案名</param>
            /// <param name="progressBar1"></param>
            /// <param name="label_Info">提示資訊 ,時時提示下載下傳多少K的 </param>
            /// <returns></returns>
            public static bool HttpDownload(string url, string path)
            {
                string tempPath = System.IO.Path.GetDirectoryName(path);
                if (!System.IO.Directory.Exists(tempPath))
                    System.IO.Directory.CreateDirectory(tempPath); 
                    string tempFile = tempPath + "/" + System.IO.Path.GetFileName(path); 
                try
                {
                    FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    // 設定參數
                    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                    //發送請求并擷取相應回應資料
                    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    //直到request.GetResponse()程式才開始向目标網頁發送Post請求
                    Stream responseStream = response.GetResponseStream();
                    //建立本地檔案寫入流
                    //Stream stream = new FileStream(tempFile, FileMode.Create);
                    byte[] bArr = new byte[1024];
                    int size = responseStream.Read(bArr, 0, (int)bArr.Length);


                    if (response.ContentLength != 0)
                    {
                        if (request.ContentLength > int.MaxValue)
                        {
                            MessageBox.Show("要下載下傳的檔案太大,超出範圍!");
                            return false;
                        }

                    }

                    while (size > 0)
                    {
                        //stream.Write(bArr, 0, size);
                        fs.Write(bArr, 0, size);
                        size = responseStream.Read(bArr, 0, (int)bArr.Length);

                        /*progressBar1.Invoke(new Action(() => {
                            progressBar1.Value += size;
                        }));*/
                    }
                    fs.Close();
                    responseStream.Close();
                //if (System.IO.File.Exists(path))
                //{
                //    System.IO.File.Delete(path);    //存在則删除
                //}
                //System.IO.File.Move(tempFile, path);

                //if (System.IO.File.Exists(tempFile))
                //{
                //    System.IO.File.Delete(tempFile);    //存在則删除
                //}
                return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

            delegate void SetTextCallBack(string text, Label txt_a);
            private static void SetText(string text, Label txt_a)
            {
                if (txt_a.InvokeRequired)
                {
                    SetTextCallBack stcb = new SetTextCallBack(SetText);
                    txt_a.Invoke(stcb, new object[] { text, txt_a });
                }
                else
                {
                    txt_a.Text = text;
                }
            }



            public static string SendGetRequest(string url)
            {
                try
                {

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.Method = "get";

                    //if (CookiesContainer == null)
                    //{
                    //    CookiesContainer = new CookieContainer();
                    //}

                    //request.CookieContainer = CookiesContainer;  //啟用cookie

                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream response_stream = response.GetResponseStream();

                    int count = (int)response.ContentLength;
                    int offset = 0;
                    byte[] buf = new byte[count];
                    while (count > 0)  //讀取傳回資料
                    {
                        int n = response_stream.Read(buf, offset, count);
                        if (n == 0) break;
                        count -= n;
                        offset += n;
                    }
                    return Encoding.UTF8.GetString(buf);
                }
                catch
                {
                    return null;
                }
            }

        }
}