聲明:最近發現不少網站引用本人的文章,竟將作者資訊都省略了,請引用本文的網站將作者不要省略作者的資訊.
/// <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