.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();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM