文件下载的一个类

网络整理 - 07-26
/// <summary>
/// 下载文件
/// </summary>
public class BDDownLoadFile
{
private string Url; //要下载的文件URL地址
private string SavePath; //要保存的文件的目录
private string errMsg; //保存错误信息
private string RegValue = @"([\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