public long DownloadFile(string FileURL,string FileSavePath)
{
long Filelength=0;
HttpWebRequest req=HttpWebRequest.create(FileURL) as HttpWebRequest;req.CookieContainer=cookie;
req.AllowAutoRedirect=true;HttpWebResponse res=req.GetResponse() as HttpWebResponse;
System.IO.Stream stream=res.GetResponseStream();
try
{
Filelength=res.ContentLength;byte [] b=new byte[512];int nReadSize=0;
nReadSize=stream.Read(b,0,512);System.IO.FileStream fs= System.IO.File.Create(FileSavePath);
try
{
while(nReadSize >0)
{
fs.Write(b,0,nReadSize);
nReadSize=stream.Read(b,0,512);
}
}
finally
{
fs.Close();
}
}
catch(Exception er)
{
Log l=new Log();
l.writelog("下载文件错误",er.ToString());
}
finally
{
res.Close();
stream.Close();
}return Filelength;
}
用以上代码下载图片文件,如果出现如下情况,即Transfer-Encoding: chunked,则文件无法下载!请教了。
HTTP/1.1 200 OK
Date: Fri, 28 Apr 2006 06:28:04 GMT
Server: IBM_HTTP_Server/6.0.2 Apache/2.0.47 (Win32)
Keep-Alive: timeout=10, max=95
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/plain
Content-Language: zh-CN
Via: 1.1 10.1.4.60 (Alteon iSD-SSL/4.0.4)
Expires: -1
Cache-Control: no-store

解决方案 »

  1.   

    private static void GetHtmlFile()
    {
    //using System.Net;
    //using System.Windows.Forms; string remoteUri = @"http://www.baidu.com/img/";
    string fileName = "logo.gif", myStringWebResource = null;
    // Create a new WebClient instance.
    WebClient myWebClient = new WebClient();
    // Concatenate the domain with the Web resource filename.
    myStringWebResource = remoteUri + fileName;
    Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);
    // Download the Web resource and save it into the current filesystem folder.
    myWebClient.DownloadFile(myStringWebResource,fileName);        
    Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource);
    Console.WriteLine("\nDownloaded file saved in the following file system folder:\n\t" + Application.StartupPath);
    Console.ReadLine(); }试试这个
      

  2.   

    如果没有特殊需要..就用webclient吧..这东西快.出现错误一般..查看一下IE下载时的数据包.. 对好了.一般就OK