使用C#从网站下载文件 [英] Download file from a website with c#

查看:99
本文介绍了使用C#从网站下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我想从网站下载文件.其实我想下载字幕.这是一些代码,此代码下载整个站点(html代码).
有谁可以帮助我吗?
谢谢,

Hi everyone,
I want to download file from a website. Actually i want to download subtitles. Here is some code, this code download whole site (html codes).
Is there anyone who can help me?
Thanks,

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;

namespace DownloadManager
{
    public partial class Form1 : Form
    {
       
        private Thread thrDownload;
        private Stream strResponse;
        private Stream strLocal;
        private HttpWebRequest webRequest;
        private HttpWebResponse webResponse;
        private static int PercentProgress;
        private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes);

        public Form1()
        {
            InitializeComponent();
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            // Let the user know we are connecting to the server
            lblProgress.Text = "Download Starting";
            // Create a new thread that calls the Download() method
            thrDownload = new Thread(Download);
            // Start the thread, and thus call Download()
            thrDownload.Start();
        }

        private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
        {
            try
            {
               
                PercentProgress = Convert.ToInt32((BytesRead * 99) / TotalBytes + 1);
               
                prgDownload.Value = PercentProgress;
               
                lblProgress.Text = "Downloaded " + BytesRead + " out of " + TotalBytes + " (" + PercentProgress + "%)";
            }
            catch (Exception exc)
            {
                lblProgress.Text = "Error :" + exc.Message;
            }
            finally
            {
                lblProgress.Text = "Download Complete!";
            }
        }

        private void Download()
        {
            using (WebClient wcDownload = new WebClient())
            {
                try
                {
                    
                    // Create a request to the file we are downloading
                    webRequest = (HttpWebRequest)WebRequest.Create(txtUrl.Text);
                    // Set default authentication for retrieving the file
                    webRequest.Credentials = CredentialCache.DefaultCredentials;
                    // Retrieve the response from the server
                    webResponse = (HttpWebResponse)webRequest.GetResponse();
                    // Ask the server for the file size and store it
                    Int64 fileSize = webResponse.ContentLength;

                    // Open the URL for download 
                    strResponse = wcDownload.OpenRead(txtUrl.Text);
                    
                    //MessageBox.Show(webResponse.StatusCode.ToString());
                    // Create a new file stream where we will be saving the data (local drive)
                    
                    strLocal = new FileStream(txtPath.Text, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);

                   
                    int bytesSize = 0;
                    
                    byte[] downBuffer = new byte[2048];

                    
                    while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                    {
                        // Write the data from the buffer to the local hard drive
                        strLocal.Write(downBuffer, 0, bytesSize);
                       
                        this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize });
                    }
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                    strResponse.Close();
                    strLocal.Close();
                }
                finally
                {
                    strResponse.Close();
                    strLocal.Close();
                }
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            
            webResponse.Close();
            strResponse.Close();
            strLocal.Close();
           
            thrDownload.Abort();
          
            prgDownload.Value = 0;
            lblProgress.Text = "Download Stopped";
        }
    }
}

推荐答案

您只需要下载一个文件?这太简单了.什么,您是否尝试过一些现有的代码进行不同类型的下载,并希望它能够解决您的问题?从头开始编写这样的简单代码难道不是很容易吗?

在过去的解决方案之一中,我提供了HTTPDownloader的完整源代码.它只下载了一个文件;并且可以恢复部分下载的文件的下载,因此当文件很大并且连接可能断开时,可以使用它.

请参阅:如何从Internet下载文件 [ ^ ].

—SA
You only need to download one file? This is way too simple. What, did you try some existing code doing different kind of downloading and hoped it will solve your problem? Wouldn''t it be easier to write such simple code from scratch?

In one of my past solutions I offered a complete source code of my HTTPDownloader; it downloaded just one file; and it can resume downloading of partially downloaded files, so you can use it when a file is big and connection is likely to break.

See: how to download a file from internet[^].

—SA


这篇关于使用C#从网站下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆