日期:2014-05-18  浏览次数:20900 次

C# 中怎样将服务器端的文件下载到客户端
C# 中怎样将服务器端的文件下载到客户端

------解决方案--------------------
C# code

  public bool downfile(string url,string LocalPath)
  {
   try
   {
    Uri u = new Uri(url);
    HttpWebRequest mRequest = (HttpWebRequest)WebRequest.Create(u);
    mRequest.Method = "GET";
    mRequest.ContentType = "application/x-www-form-urlencoded";

    HttpWebResponse wr = (HttpWebResponse)mRequest.GetResponse();

    Stream sIn = wr.GetResponseStream();
    FileStream fs = new FileStream(LocalPath, FileMode.Create, FileAccess.Write);

    long length = wr.ContentLength;
    long i = 0;
    decimal j=0;
    
    while (i < length)
    {
     byte[] buffer = new byte[1024];
     i += sIn.Read(buffer, 0, buffer.Length);
     fs.Write(buffer, 0, buffer.Length);
     
     if((i % 1024)==0)
     {
      j=Math.Round(Convert.ToDecimal((Convert.ToDouble(i)/Convert.ToDouble(length))*100),4);
      statusBar1.Text="当前下载文件大小:"+length.ToString()+"字节   当前下载大小:"+i+"字节 下载进度"+j.ToString()+"%";
      
     }
     else
     {
      statusBar1.Text="当前下载文件大小:"+length.ToString()+"字节   当前下载大小:"+i+"字节";
     }
     
    }

    sIn.Close();
    wr.Close();
    fs.Close();
    return true;
   }
   catch { return false; }
  }

------解决方案--------------------
不懂C#只能给梅子顶
------解决方案--------------------
C# codepublicbool downfile(string url,string LocalPath)
{try
{
Uri u=new Uri(url);
HttpWebRequest mRequest= (HttpWebRequest)WebRequest.Create(u);
mRequest.Method="GET";
mRequest.ContentType="application/x-www-form-urlencoded";

HttpWebResponse wr= (HttpWebResponse)mRequest.GetResponse();

Stream sIn= wr.GetResponseStream();
FileStream fs=new FileStream(LocalPath, FileMode.Create, FileAccess.Write);long length= wr.ContentLength;long i=0;decimal j=0;while (i < length)
{byte[] buffer=newbyte[1024];
i+= sIn.Read(buffer,0, buffer.Length);
fs.Write(buffer,0, buffer.Length);if((i%1024)==0)
{
j=Math.Round(Convert.ToDecimal((Convert.ToDouble(i)/Convert.ToDouble(length))*100),4);
statusBar1.Text="当前下载文件大小:"+length.ToString()+"字节 当前下载大小:"+i+"字节 下载进度"+j.ToString()+"%";

}else
{
statusBar1.Text="当前下载文件大小:"+length.ToString()+"字节 当前下载大小:"+i+"字节";
}
 
}

sIn.Close();
wr.Close();
fs.Close();returntrue;
}catch {returnfalse; }


OK
------解决方案--------------------
ftpwebrequest下载文件
string filePath = @""; 
const string url = ""; 
try 

using (WebClient wc = new WebClient()) 

string html = wc.DownloadString(url); 
using (StreamWriter writer = new StreamWriter(filePath,false,wc.Encoding)) 

writer.Write(html); 
writer.Flush(); 



catch (Exception ex) 

Console.WriteLine(ex.Message); 

Console.Read();