/// <summary>
/// 下载外网文件
/// </summary>
/// <param name="url">下载文件地址</param>
/// <param name="filename">下载后另存为(全路径)</param>
/// <param name="errmsg">错误消息</param>
public bool DownloadFile(string url, string filename,ref string errmsg)
{
try
{
if (!File.Exists(filename))
{
System.IO.FileStream f = System.IO.File.Create(filename);
f.Close();
f.Dispose();
}
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();
System.IO.Stream st = webResponse.GetResponseStream();
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
System.IO.Stream stream = new System.IO.FileStream(filename, System.IO.FileMode.Create);
while (osize > 0)
{
stream.Write(by, 0, osize);
osize = st.Read(by, 0, (int)by.Length);
}
stream.Close();
st.Close();
webResponse.Close();
webRequest.Abort();
return true;
}
catch (System.Exception e)
{
errmsg = e.Message;
return false;
}
}
调用示例:
var errmsg = string.Empty;
var flag = DownloadFile("http://www.baidu.com/***.pdf", @"D:\***.pdf",ref errmsg);
c#下载外网文件
于 2022-02-08 17:23:07 首次发布