從網路路徑下載檔案
阿新 • • 發佈:2019-01-07
1.根據網路路徑下的共享資料夾下載檔案。
2.程式碼
(1)直接下載
WebClient wc = new WebClient() { //Credentials = new NetworkCredential("Administrator", "Iphone6") Credentials = CredentialCache.DefaultCredentials }; wc.DownloadFile(@"\\192.168.1.131\share\"+filename,@"D:\"+filename);
WebClient的DownloadFile(網路路徑位置,待儲存位置)
(2)分片下載(可能需要使用者名稱密碼認證)
WebClient client = new WebClient() { //Credentials = new NetworkCredential("Administrator", "Iphone6") Credentials = CredentialCache.DefaultCredentials }; Stream str = client.OpenRead(@"\\192.168.1.131\share\" + filename); StreamReader reader = new StreamReader(str); int allmybyte = (int)reader.BaseStream.Length; byte[] mbyte = new byte[allmybyte]; int length = 4 * 1024 * 1024; int startmbyte = 0; while (allmybyte > 0) { if (allmybyte<length) { length = allmybyte; } //Task<int> m = str.ReadAsync(mbyte, startmbyte, length); int m = str.Read(mbyte, startmbyte, length); if (m == 0) break; startmbyte += m; allmybyte -= m; } reader.Dispose(); str.Dispose(); string path = @"F:\" + filename; FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); fstr.Write(mbyte, 0, startmbyte); fstr.Flush(); fstr.Close();