/// <summary>
/// 下载文件
/// </summary>
public class bddownloadfile
{
private string url; //要下载的文件url地址
private string savepath; //要保存的文件的目录
private string errmsg; //保存错误信息
private string regvalue = @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
private string savefile; //生成的文件
public bddownloadfile(string url,string path)
{
url = url;
savepath = path;
this.savefile = getfilename();
}
/// <summary>
/// 返回错误信息
/// </summary>
public string errormessage
{
get
{
return this.errmsg;
}
}
public string getsavefile
{
get
{
return this.savefile;
}
}
public bool downloadfile()
{
bool result = true;
if( !checkurl(this.url) )
{
this.errmsg = "网址不合法!";
return false;
}
webclient objwc = new webclient();
objwc.credentials = credentialcache.defaultcredentials;
try
{
byte[] tmpdata = objwc.downloaddata(this.url);
if(tmpdata.length > 0)
{
filestream objfs = new filestream(this.savefile,filemode.create);
objfs.write(tmpdata,0,(int)tmpdata.length); //向文件写入数据
objfs.close();
this.errmsg = "有数据!";
}
else
{
result = false;
this.errmsg = "没有接收到任何数据!";
}
}
catch(system.net.webexception e)
{
this.errmsg += "<li>下载数据时发生错误!" + e.message;
return false;
}
catch(system.uriformatexception e)
{
this.errmsg += "<li>访问的网址无效!" + e.message;
return false;
}
catch(exception e)
{
this.errmsg = "错误信息:<li>."+e.message;
result = false;
}
finally
{
objwc.dispose();
}
return result;
}
/// <summary>
/// 检查网址是否合法
/// </summary>
/// <param name="chkurl">要检查的网址</param>
/// <returns></returns>
private bool checkurl(string chkurl)
{
regex reg = new regex(regvalue);
match match = reg.match(chkurl);
return match.success;
}
/// <summary>
/// 取得网址是否有文件,如果有文件,则处理,若没有,则返回.html
/// </summary>
/// <param name="chkurl"></param>
/// <returns></returns>
private string getfiletype(string chkurl)
{
if(chkurl.lastindexof("/") == (chkurl.length-1)) //没有具体文件
return "html";
int j = 0;
for(int i = 0; i < chkurl.length; i++)
{
if(chkurl.indexof("/",i)>-1)
{
i = chkurl.indexof("/",i);
j++;
}
}
if( j < 3)
return "html";
//取得"/"后的字符,然后得出文件类型
string end = chkurl.substring(chkurl.lastindexof(".")+1);
switch(end)
{
case "asp":
case "aspx":
case "jsp":
case "php":
return "html";
default:
return end;
}
}
private string getfilename()
{
string filename = this.savepath + "\\" + system.datetime.now.year.tostring()+system.datetime.now.month.tostring()+system.datetime.now.day.tostring()+system.datetime.now.minute.tostring()+system.datetime.now.second.tostring()+common.makerandom(4).tostring()+"."+getfiletype(this.url);
for(;file.exists(filename);)
{
filename = this.savepath + "\\" + system.datetime.now.year.tostring()+system.datetime.now.month.tostring()+system.datetime.now.day.tostring()+system.datetime.now.minute.tostring()+system.datetime.now.second.tostring()+common.makerandom(4).tostring()+"\\"+getfiletype(this.url);
}
return filename;
}
} //bddownloadfile end
