.net通过网络路径下载文件至本地

获取网络文件,通过流保存文件,由于上一版存在数据丢失情况,稍微调整了以下。

//网络路径文件
string pathUrl = "http://localhost:805/春风吹.mp3";
System.Net.HttpWebRequest request = null;
System.Net.HttpWebResponse response = null;
//请求网络路径地址
request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(pathUrl);
request.Timeout = 5000; // 超时时间
//获得请求结果
response = (System.Net.HttpWebResponse)request.GetResponse();
//文件下载地址
string path = "/文件下载";
// 如果不存在就创建file文件夹
if (!Directory.Exists(path))
{
if (path != null) Directory.CreateDirectory(path);
}
path = path + "/春风吹.mp3";
Stream stream = response.GetResponseStream();
//先创建文件
Stream sos = new System.IO.FileStream(path, System.IO.FileMode.Create);
byte[] img = new byte[1024];
int total = stream.Read(img, 0, img.Length);
while (total > 0)
{
//之后再输出内容
sos.Write(img, 0, total);
total = stream.Read(img, 0, img.Length);
}
stream.Close();
stream.Dispose();
sos.Close();
sos.Dispose();

.net通过网络路径下载文件至本地

全文结束