C#winform 實現從服務器下載

      /// <summary>
        /// 下載服務器文件至客戶端(不帶進度條)
        /// </summary>
        /// <param name="strUrlFilePath">要下載的Web服務器上的文件地址(全路徑 如:http://www.dzbsoft.com/test.rar)</param>
        /// <param name="Dir">下載到的目錄(存放位置,機地機器文件夾)</param>
        /// <returns>True/False是否上傳成功</returns>
        public bool DownLoadFile(string strUrlFilePath, string strLocalDirPath)
        {
            // 創建WebClient實例
            WebClient client = new WebClient();
            //被下載的文件名
            string fileName = strUrlFilePath.Substring(strUrlFilePath.LastIndexOf("/"));
            //另存爲的絕對路徑+文件名
            string Path = strLocalDirPath + fileName;
            try
            {
                WebRequest myWebRequest = WebRequest.Create(strUrlFilePath);
            }
            catch (Exception exp)
            {
                MessageBox.Show("文件下載失敗:" + exp.Message, "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            try
            {
                client.DownloadFile(strUrlFilePath, Path);
                return true;
            }
            catch (Exception exp)
            {
                MessageBox.Show("文件下載失敗:" + exp.Message, "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }


        /// <summary>
        /// 下載帶進度條代碼(普通進度條)
        /// </summary>
        /// <param name="URL">網址</param>
        /// <param name="Filename">文件名</param>
        /// <param name="Prog">普通進度條ProgressBar</param>
        /// <returns>True/False是否下載成功</returns>
        public bool DownLoadFile(string URL, string Filename, ProgressBar Prog)
        {
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); //從URL地址得到一個WEB請求   
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); //從WEB請求得到WEB響應   
                long totalBytes = myrp.ContentLength; //從WEB響應得到總字節數   
                Prog.Maximum = (int)totalBytes; //從總字節數得到進度條的最大值   
                System.IO.Stream st = myrp.GetResponseStream(); //從WEB請求創建流(讀)   
                System.IO.Stream so = new System.IO.FileStream(Filename, System.IO.FileMode.Create); //創建文件流(寫)   
                long totalDownloadedByte = 0; //下載文件大小   
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length); //讀流   
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte; //更新文件大小   
                    Application.DoEvents();
                    so.Write(by, 0, osize); //寫流   
                    Prog.Value = (int)totalDownloadedByte; //更新進度條   
                    osize = st.Read(by, 0, (int)by.Length); //讀流   
                }
                so.Close(); //關閉流
                st.Close(); //關閉流
                return true;
           }
            catch
            {
                return false;
            }
        }




        /// <summary>
        /// 下載帶進度條代碼(狀態欄式進度條)
        /// </summary>
        /// <param name="URL">網址</param>
        /// <param name="Filename">文件名</param>
        /// <param name="Prog">狀態欄式進度條ToolStripProgressBar</param>
        /// <returns>True/False是否下載成功</returns>
        public bool DownLoadFile(string URL, string Filename, ToolStripProgressBar Prog)
        {
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); //從URL地址得到一個WEB請求   
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); //從WEB請求得到WEB響應   
                long totalBytes = myrp.ContentLength; //從WEB響應得到總字節數   
                Prog.Maximum = (int)totalBytes; //從總字節數得到進度條的最大值   
                System.IO.Stream st = myrp.GetResponseStream(); //從WEB請求創建流(讀)   
                System.IO.Stream so = new System.IO.FileStream(Filename, System.IO.FileMode.Create); //創建文件流(寫)   
                long totalDownloadedByte = 0; //下載文件大小   
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length); //讀流   
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte; //更新文件大小   
                    Application.DoEvents();
                    so.Write(by, 0, osize); //寫流   
                    Prog.Value = (int)totalDownloadedByte; //更新進度條   
                    osize = st.Read(by, 0, (int)by.Length); //讀流   
                }
                so.Close(); //關閉流   
                st.Close(); //關閉流   
                return true;
            }
            catch
            {
                return false;
            }

        }



        public void startProcess(string fileName)
        {
            //定義一個ProcessStartInfo實例

            System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();

            //設置啓動進程的初始目錄

            info.WorkingDirectory = Application.StartupPath;

            //設置啓動進程的應用程序或文檔名

            info.FileName = @fileName;

            //設置啓動進程的參數

            info.Arguments = "";

            //啓動由包含進程啓動信息的進程資源

            try
            {

                System.Diagnostics.Process.Start(info);

            }

            catch (System.ComponentModel.Win32Exception we)
            {

                MessageBox.Show(this, we.Message);

                return;

            }
        }
 
 
 
 
 
一、//TransmitFile實現下載
protected void Button1_Click(object sender, EventArgs e)
{
/*
微軟爲Response對象提供了一個新的方法TransmitFile來解決使用Response.BinaryWrite
下載超過400mb的文件時導致Aspnet_wp.exe進程回收而無法成功下載的問題。
代碼如下:
*/
Response.ContentType
= "application/x-zip-compressed";
Response.AddHeader(
"Content-Disposition", "attachment;filename=z.zip");
string filename = Server.MapPath("DownLoad/z.zip");
Response.TransmitFile(filename);
}

二、
//WriteFile實現下載
protected void Button2_Click(object sender, EventArgs e)
{
/*
using System.IO;

*/
string fileName = "asd.txt";//客戶端保存的文件名
string filePath = Server.MapPath("DownLoad/aaa.txt");//路徑

FileInfo fileInfo
= new FileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader(
"Content-Disposition", "attachment;filename=" + fileName);
Response.AddHeader(
"Content-Length", fileInfo.Length.ToString());
Response.AddHeader(
"Content-Transfer-Encoding", "binary");
Response.ContentType
= "application/octet-stream";
Response.ContentEncoding
= System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
}

三、
//WriteFile分塊下載
protected void Button3_Click(object sender, EventArgs e)
{
string fileName = "aaa.txt";//客戶端保存的文件名
string filePath = Server.MapPath("DownLoad/aaa.txt");//路徑

System.IO.FileInfo fileInfo
= new System.IO.FileInfo(filePath);

if (fileInfo.Exists == true)
{
const long ChunkSize = 102400;//100K 每次讀取文件,只讀取100K,這樣可以緩解服務器的壓力
byte[] buffer = new byte[ChunkSize];

Response.Clear();
System.IO.FileStream iStream
= System.IO.File.OpenRead(filePath);
long dataLengthToRead = iStream.Length;//獲取下載的文件總大小
Response.ContentType = "application/octet-stream";
Response.AddHeader(
"Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
while (dataLengthToRead > 0 && Response.IsClientConnected)
{
int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//讀取的大小
Response.OutputStream.Write(buffer, 0, lengthRead);
Response.Flush();
dataLengthToRead
= dataLengthToRead - lengthRead;
}
Response.Close();
}
}

四、
//流方式下載
protected void Button4_Click(object sender, EventArgs e)
{
string fileName = "aaa.txt";//客戶端保存的文件名
string filePath = Server.MapPath("DownLoad/aaa.txt");//路徑

//以字符流的形式下載文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes,
0, bytes.Length);
fs.Close();
Response.ContentType
= "application/octet-stream";
//通知瀏覽器下載文件而不是打開
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}

//----------------------------------------------------------

public void DownloadFile( System.Web.UI.Page WebForm,String FileNameWhenUserDownload ,String FileBody )
{

  WebForm.Response.ClearHeaders();
  WebForm.Response.Clear();
  WebForm.Response.Expires
= 0;
  WebForm.Response.Buffer
= true;
  WebForm.Response.AddHeader(
"Accept-Language", "zh-tw");
  
//'文件名稱
  WebForm.Response.AddHeader("content-disposition", "attachment; filename='"+System.Web.HttpUtility.UrlEncode(FileNameWhenUserDownload, System.Text.Encoding.UTF8)+"'");
  WebForm.Response.ContentType
= "Application/octet-stream";
  
//'文件內容
  WebForm.Response.Write(FileBody);//-----------
WebForm.Response.End();
}

//上面這段代碼是下載一個動態產生的文本文件,若這個文件已經存在於服務器端的實體路徑,則可以通過下面的函數:

public void DownloadFileByFilePath( System.Web.UI.Page WebForm,String FileNameWhenUserDownload ,String FilePath )
{
  WebForm.Response.ClearHeaders();
  WebForm.Response.Clear();
  WebForm.Response.Expires
= 0;
WebForm.Response.Buffer
= true;
  WebForm.Response.AddHeader(
"Accept-Language", "zh-tw");
  
//文件名稱
  WebForm.Response.AddHeader("content-disposition", "attachment; filename='" + System.Web.HttpUtility.UrlEncode(FileNameWhenUserDownload, System.Text.Encoding.UTF8) +"'" );
  WebForm.Response.ContentType
= "Application/octet-stream";
  
//文件內容
  WebForm.Response.Write(System.IO.File.Rea}dAllBytes(FilePath));//---------
  WebForm.Response.End();

發佈了29 篇原創文章 · 獲贊 41 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章