利用代码实现下载文件

@zgcwkj  2019年04月14日

C# 可以直接调用此代码,直接下载文件,等下载功能

直接上代码:(根据需要添加请求头、UA 和 Cookie 等)

/// <summary>
/// 下载文件
/// </summary>
/// <param name="Url">请求地址</param>
/// <param name="FileName">下载后的存放地址</param>
public static bool DownloadFile(string Url, string FileName)
{
    float percent = 0;
    try
    {
        HttpWebRequest Myrq = (HttpWebRequest)HttpWebRequest.Create(Url);
        Myrq.Referer = Url;
        HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse();
        long totalBytes = myrp.ContentLength;
        System.IO.Stream st = myrp.GetResponseStream();
        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;
            so.Write(by, 0, osize);
            osize = st.Read(by, 0, (int)by.Length);
            percent = (float)totalDownloadedByte / (float)totalBytes * 100;
            Console.Write(percent.ToString("00") + " ");
        }
        so.Close();
        st.Close();
        Console.WriteLine("完成");
        return true;
    }
    catch (Exception e)
    {
        Console.WriteLine("失败,原因:" + e.Message);
        return false;
    }
}


添加新评论

Top