C# 下载远程文件

方法一:

try  

{  

string savePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "temp");  

if (!Directory.Exists(savePath))  

    {  

        Directory.CreateDirectory(savePath);  

    }  

using (WebClient webClient = new WebClient())  

    {  

        webClient.DownloadFile(FullFilePath, Path.Combine(savePath, FileName));  

    }  

return true;  

}  

catch  

{  

return false;  

 

 

方法二:

bool flag = false;  

string savePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "temp");  

try  

{  

if (!Directory.Exists(savePath))  

    {  

        Directory.CreateDirectory(savePath);  

    }  

using (FileStream fileStream = new FileStream(Path.Combine(savePath, FileName), FileMode.Create, FileAccess.Write))  

    {  

//创建请求  

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FullFilePath);  

//接收响应  

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();  

//输出流  

        Stream responseStream = response.GetResponseStream();  

byte[] bufferBytes = new byte[10000];//缓冲字节数组  

int bytesRead = -1;  

while ((bytesRead = responseStream.Read(bufferBytes, 0, bufferBytes.Length)) > 0)  

        {  

            fileStream.Write(bufferBytes, 0, bytesRead);  

        }  

if (fileStream.Length > 0)  

        {  

            flag = true;  

        }  

//关闭写入  

        fileStream.Flush();  

        fileStream.Close();  

    }  

}  

catch (Exception ex)  

{  

//返回错误消息  

throw ex;  

}  

return flag;

posted @ 2017-10-18 16:41  cbinqin  阅读(1052)  评论(0编辑  收藏  举报