通过Http下载文件(CS)

1、需要引用System.Net.dll

///<summary>
/// 下载文件
/// </summary>
/// <param name="URL">下载文件地址</param>
/// <param name="Filename">下载后另存为(全路径)</param>
private bool DownloadFile(string URL, string filename)
{
    try
    {
        HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
        HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
        Stream st = myrp.GetResponseStream();
        Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
        byte[] by = new byte[1024];
        int osize = st.Read(by, 0, (int)by.Length);
        while (osize > 0)
        {
          so.Write(by, 0, osize);
          osize = st.Read(by, 0, (int)by.Length);
        }
        so.Close();
        st.Close();
        myrp.Close();
        Myrq.Abort();
        return true;
    }
    catch (System.Exception e)
    {
        return false
    }
}
0%