这是我写的下载类
using System;
using System.Net;
using System.IO;namespace FengYu.FileDownload
{
public class Downloader
{
private const int downloadBlockSize = 1024;
public void DownloadFile()
{
if (this.fileLocalPath == null)
return;
try
{
// create the download buffer
byte[] buffer = new byte[downloadBlockSize];
int readCount;
// read a block of bytes and get the number of bytes read
while((int)(readCount = DownloadStream.Read(buffer, 0, downloadBlockSize)) > 0)
{
// save block to end of file
SaveToFile(buffer, readCount, this.fileLocalPath);
// update total bytes read
totalDownloaded += readCount;
}
}
finally
{
if( response != null)
response.Close();
this.isFileDownload = true; 
}
// return true;
} //将数据流保存到本地文件
private void SaveToFile(byte[] buffer, int count, string fileName)
{
FileStream f = null; try
{
f = File.Open(fileName, FileMode.Append, FileAccess.Write);
f.Write(buffer, 0, count);
}
finally
{
if(f != null)
f.Close();
}
} public void Connect()
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(this.url);
response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.NotFound )
{
this.isFileExist = false;
return ;
}
if (response.StatusCode == HttpStatusCode.OK)
{
fileSize = response.ContentLength;
fileLastModifyInInternet = response.LastModified;
this.isFileExist = true;
}
}
private long fileSize;  //文件大小
private string fileLocalPath; //文件本地路径
private DateTime fileLastModifyOnLocal;  //本地最后修改时间
private DateTime fileLastModifyInInternet;  //网上最后修改时间
private HttpWebResponse response;  
private Stream stream;  //取得返回流
private long start;  //文件中下载点
private bool isFileExist;  //网络中文件是否存在?
private bool isFileDownload;  //文件是否下载完成?
private string url;  //文件的网络地址
private long totalDownloaded; //已下载的数据量 #region  //定义属性
public Stream DownloadStream
{
get
{
if(this.start == this.fileSize)
return Stream.Null;
if(this.stream == null)
this.stream = this.response.GetResponseStream();
return this.stream;
}
} public long TotalDownloaded
{
get
{
return this.totalDownloaded;
}
}
public string FileLocalPath  //本地文件路径
{
set
{
this.fileLocalPath = value;
}
get
{
return this.fileLocalPath;
}
}
public string Url //下载文件的网络地址
{
set
{
this.url = value;
}
get
{
return this.url;
}
}
public bool IsFileExist   //互联网上文件是否存在?
{
get
{
return this.isFileExist;
}
}
public bool IsFileDownload  //文件是否已下载完成
{
get
{
return this.isFileDownload;
}
}
public long FileSize  //文件大小
{
get
{
return this.fileSize ;
}
}
public DateTime FileLastModifyOnLocal  //本地中文件最近下载的时间
{
set
{
this.fileLastModifyOnLocal = value;
}
get
{
return this.fileLastModifyOnLocal ;
}
}
public DateTime FileLastModifyInInternet  //互联网中文件最近修改的时间
{
get
{
return this.fileLastModifyInInternet ;
}
}
#endregion public void Close()
{
this.response.Close();
}
}
}
下面是调用类的窗体的主要代码:
[STAThread]
static void Main() 
{
Application.Run(new Form1());
} private Thread mythread; private void Download_Click(object sender, System.EventArgs e)
{


FileOne.FileLocalPath = LocalPathOfFile.Text;
FileOne.Url = UrlOfFile.Text;
FileOne.Connect();
if (FileOne.IsFileExist == false)
return;
progressBarDownload.Minimum = 0;
progressBarDownload.Maximum = (int)FileOne.FileSize;
timer1.Enabled = true;
txtBoxMessage.Text = FileOne.FileSize.ToString();
mythread = new Thread(new ThreadStart(FileOne.DownloadFile));
mythread.Start();

}
private Downloader FileOne = new Downloader();
private void timer1_Tick(object sender, System.EventArgs e)
{
if (FileOne.IsFileDownload == true)
{
txtBoxMessage.Text += "下载已完成!";
timer1.Stop();
}
long percentD ;
percentD = FileOne.TotalDownloaded * 100/FileOne.FileSize;
labelDownloadPercent.Text = percentD.ToString() + "%";
progressBarDownload.Value = (int)FileOne.TotalDownloaded;
}
1、上面的代码下载几百k的文件的时候没有什么问题,但是在天极网下载文件(如http://dl1.mydown.com/soft1/200507/FlashFXP_3.2.0.1080_SC.exe)的时候却屡屡出错,编译环境提示 “while((int)(readCount = DownloadStream.Read(buffer, 0, downloadBlockSize)) > 0)”超时等待,估计是网络堵塞的原因。不知各位兄弟姐妹有何解决方法?
2、在下载天空软件上的文件时(如http://conut.skycn.com/softdownload.php?id=15809&url=http://jsyz.driversky.com/down/eMule-0.46c-VeryCD0913Install.exe,实际用的url是http://jsyz.driversky.com/down/eMule-0.46c-VeryCD0913Install.exe)返回的文件大小只有4720字节,这是不是因为地址转向造成的,如何解决?

解决方案 »

  1.   

    标记一下。
    ====CSDN 小助手 V2.5 2005年11月05日发布====
    CSDN小助手是一款脱离浏览器也可以访问Csdn论坛的软件
    界面:http://blog.csdn.net/Qqwwee_Com/archive/2005/11/05/523395.aspx
    下载:http://szlawbook.com/csdnv2
      

  2.   

    你看看我作过的部分代码:你可能要超时处理吧
    public override HttpWebResponse GetResponse(string id)
    {
    TraceEx.Debug("IN");

    string uri = this.OriginalUri;
    TraceEx.Debug("OriginalUri: ", uri);
    TraceEx.Debug("id: ", id); if (!SplittingProp.RegexHost.IsMatch(this.Host))
    {
    ErrorCode ec = new Service_ParamInvalidValue(new ArgumentOutOfRangeException("Host", ErrorMessage.ERROR_HOST_OUT_OF_RANGE),
    MINOR_CODE + 01);
    AppErrorException aee = new AppErrorException(ec, PackageName.PACKAGENAME_SPLITTING,
    ErrorMessage.ERROR_HOST_OUT_OF_RANGE, " Host[", this.Host, "]");
    throw aee;
    } HttpWebRequest netReq = null;
    try
    {
    netReq = (HttpWebRequest) HttpWebRequest.Create(uri);
    }
    catch (UriFormatException ex)
    {
    ErrorCode ec = new Service_DataFormatError(ex, MINOR_CODE + 02);
    AppErrorException aee = new AppErrorException(ec, PackageName.PACKAGENAME_SPLITTING,
    ErrorMessage.ERROR_URI_FORMAT_ERROR, " Uri[", uri, "]");
    throw aee;
    } netReq.Method = SplConst.HTTP_POST;
    netReq.ConnectionGroupName = id;
    SetHeader(netReq); string strProxy = SplittingProp.UrlProxy;
    if (strProxy.Length != 0)
    {
    TraceEx.Debug("Proxy:", strProxy);
    netReq.Proxy = new WebProxy(strProxy);
    }
    Stream stream = netReq.GetRequestStream();
    stream.Write(Body, 0, Body.Length);
    stream.Close();

    HttpWebResponse netResp = null;
    try
    {
    netResp = (HttpWebResponse) netReq.GetResponse();

    catch (WebException we)
    {
    if (we.Response != null)
    {
    TraceEx.Warn(PackageName.PACKAGENAME_SPLITTING, "->", ErrorMessage.WARN_ERROR_RESPONSE_RETURN, " Ignored.", " : StatusCode[",
    we.Status, "]", " Message[",we.Message,"]");
    netResp = (HttpWebResponse) we.Response;
    //we.Response.Close();

    else 
    {
    ErrorCode ec = new Service_CommunicateFail(we, MINOR_CODE + 03);
    AppErrorException aee = new AppErrorException(ec, PackageName.PACKAGENAME_SPLITTING,
    ErrorMessage.ERROR_GETRESPONSE_ERROR, " Uri[", uri,"]");
    throw aee;
    }
    }
    TraceEx.Debug("OUT");
    return netResp;
    }
      

  3.   

    to cw888() :
       我看了您的代码,感觉读起来有些困难,可能是初学的缘故,如果可以,再多给点代码和说明好吗?
      

  4.   


    请参考我尾巴后面的软件
    有源代码的。====CSDN 小助手 V2.5 2005年11月05日发布====
    CSDN小助手是一款脱离浏览器也可以访问Csdn论坛的软件
    界面:http://blog.csdn.net/Qqwwee_Com/archive/2005/11/05/523395.aspx
    下载:http://szlawbook.com/csdnv2
      

  5.   

    我也碰到类似的问题,下载其他的文件没有问题,但是下载扩展名为.cs,.vb(.net的文件)总是出问题,但是更改他们的扩展名后就可以正常下载,望大虾解决。