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

求用webclient 下载文件用法

  用   webclient   下载远程文件到本地机器   为什么总报错   我把同样的代码移植到windows   form   下   就没问题   请高手帮忙        
代码如下

string   URL   =   srcAddress.Text;
int   n   =   URL.LastIndexOf( '/ ');
string   URLAddress   =   URL.Substring(0,n);
string   fileName   =   URL.Substring(n+1,URL.Length-n-1);
string   Dir   =   tarAddress.Text;
if(!Directory.Exists(Dir))
{
System.IO.Directory.CreateDirectory(Dir);
}
  string   Path   =   Dir+ '\\ '+fileName;
client.DownloadFile(URL,Path);



------解决方案--------------------
如果你计算路径没有问题。如果目录有权限,如果图片允许匿名下载,应该可以下载的,例子
<%@ Page Language= "C# " EnableViewState= "true " %>
<%@ Import Namespace= "System.Net " %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<script runat= "server ">

protected void Button1_Click( object sender, EventArgs e )
{
string strUrl;
strUrl = " ";
WebClient wc = new WebClient();
wc.DownloadFile( "http://dotnet.aspx.cc/Images/logoSite.gif ",@ "C:\Inetpub\wwwroot\xx.gif ");

}

</script>

<html xmlns= "http://www.w3.org/1999/xhtml ">
<head runat= "server ">
<title> 文件 </title>
</head>
<body>
<form id= "MengXianhui " runat= "server ">

<asp:Button ID= "btnUpload " runat= "server " Text= "下载 " OnClick= "Button1_Click "> </asp:Button>
<p>
<asp:Label ID= "Msg " runat= "server " ForeColor= "Red "> </asp:Label> </p>
</form>
</body>
</html>