我在做一個(gè)下載程序,用戶(hù)導(dǎo)入一個(gè)下載列表,列表中的文件部分可能已經(jīng)下過(guò)了,如果本地文件大小和遠(yuǎn)程文件大小一樣,就不再下載一次了。
但是在我測(cè)試時(shí),卻發(fā)生一個(gè)奇怪的事,本地的文件竟然比遠(yuǎn)程的文件大,比如本地4881,遠(yuǎn)程的卻是4880,前后也就差這么一兩分鐘,遠(yuǎn)程文件不可能大小變化的呀。這個(gè)1是從哪里來(lái)的呢。
下面是我的三個(gè)主要函數(shù)。
/// <summary> /// get local file length /// </summary> /// <param name="filename">local file name</param> /// <returns>file length</returns> public static long GetLocalFileLength(string filename) { long length=0; try { FileInfo finfo = new FileInfo(filename); length = finfo.Length; } catch { length = -1; } return length; } /// <summary> /// get remote file length /// </summary> /// <param name="fileurl">file url</param> /// <returns>file length of long type</returns> public static long GetRemoteFileLength(string fileurl) { long length = 0; HttpWebResponse resp = null; StreamReader sr = null; try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(fileurl); req.UserAgent = "netclient"; resp = (HttpWebResponse)req.GetResponse(); length = resp.ContentLength; if (length == -1) { sr = new StreamReader(resp.GetResponseStream()); length = sr.ReadToEnd().Length; } } catch { length = -1; } finally { if (sr != null) sr.Close(); if (resp != null) resp.Close(); } return length; }public static void DownloadFile(string savepath, string url) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.UserAgent = "netclient"; WebResponse resp = req.GetResponse(); Stream stream = resp.GetResponseStream(); FileStream fs = new FileStream(savepath, FileMode.Create); byte[] nbytes = new byte[512]; int nReadSize = 0; nReadSize = stream.Read(nbytes, 0, 512); while (nReadSize > 0) { fs.Write(nbytes, 0, nReadSize); nReadSize = stream.Read(nbytes, 0, 512); } fs.Close(); stream.Close(); resp.Close(); return; }
?
2 回答

翻翻過(guò)去那場(chǎng)雪
TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
diff一下,看看兩個(gè)文件之間有什么區(qū)別。Visual Studio SDK里面。

四季花海
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個(gè)贊
下載文件可以直接使用?WebClient 類(lèi)的?DownloadFile 方法,如下:
?new WebClient().DownloadFile(url, savePath);
用這個(gè)簡(jiǎn)單也不會(huì)出錯(cuò),試試看吧!
- 2 回答
- 0 關(guān)注
- 1188 瀏覽
添加回答
舉報(bào)
0/150
提交
取消