提示:C# 代码下载文件到本地
/// <summary>
/// 下载线上文件到本地
/// </summary>
/// <param name="URL">下载文件链接</param>
/// <param name="filename">保存到本地的地址</param>
/// <returns></returns>
public static void DownloadFile(string URL, string filename)
{
HttpWebRequest req = null;
HttpWebResponse rep = null;
Stream st = null;
Stream so = null;
try
{
req = (HttpWebRequest)WebRequest.Create(URL);//请求网络资源
req.UserAgent = "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Mobile Safari/537.36";
rep = (HttpWebResponse)req.GetResponse();//返回Internet资源的响应
long totalBytes = rep.ContentLength;//获取请求返回内容的长度
st = rep.GetResponseStream();//读取服务器的响应资源,以IO流的形式进行读写
so = new FileStream(filename, 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);//读取当前字节流的总长度
}
so.Flush();
}
catch (Exception ex) { ex.ToString(); }
finally
{
if (so != null) { so.Close(); so.Dispose(); }
if (st != null) { st.Close(); st.Dispose(); }
if (rep != null) { rep.Close(); rep.Dispose(); }
if (req != null) { req.Abort(); }
}
}