我在做一个下载程序,用户导入一个下载列表,列表中的文件部分可能已经下过了,如果本地文件大小和远程文件大小一样,就不再下载一次了。
但是在我测试时,却发生一个奇怪的事,本地的文件竟然比远程的文件大,比如本地4881,远程的却是4880,前后也就差这么一两分钟,远程文件不可能大小变化的呀。这个1是从哪里来的呢。
下面是我的三个主要函数。
/// <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;
}
diff一下,看看两个文件之间有什么区别。Visual Studio SDK里面。
下载文件可以直接使用 WebClient 类的 DownloadFile 方法,如下:
new WebClient().DownloadFile(url, savePath);
用这个简单也不会出错,试试看吧!