namespace DownRemoteFile
{
class DownFile
{
#region 成员变量
private string savePath;
private bool newName;
#endregion
#region 属性
public string SavePath
{
set
{
savePath=value.Replace("/", "\");
if (savePath.LastIndexOf("\") != savePath.Length - 1)
savePath += "\";
}
get
{
return savePath;
}
}
public bool NewName
{
set { newName = value; }
get { return newName; }
}
#endregion
#region 构造函数
public DownFile()
{
newName = false;
savePath = "c:\";
}
#endregion
#region 私有方法
///
/// 随机返回文件名
///
///
private string getFileName()
{
System.Random objDom = new Random();
int intNum = objDom.Next(1000, 9999);
objDom = null;
string strNum = System.DateTime.Now.ToString("yyyyMMddhhmmss");
return strNum + intNum.ToString();
}
///
/// 根据文件得到文件扩展名
///
/// 文件名
///
private string getExtension(string fileName)
{
int start=fileName.IndexOf(".")+1;
string Ext = fileName.Substring(start, fileName.Length - start);
return Ext;
}
#endregion
#region 公共方法
///
/// 保存远程文件
///
/// 远程文件路径
///
public string SaveFile(string filePath)
{
string fPath, fName, sPath;
fPath = filePath.Replace("\", "/");
int start = fPath.LastIndexOf("/") + 1;
fName = fPath.Substring(start, fPath.Length - start);
if (newName)
{
sPath = savePath + getFileName() + "." + getExtension(fName);
}
else
{
sPath = savePath + fName;
}
System.Net.WebClient myWebClient = new System.Net.WebClient();
try
{
myWebClient.DownloadFile(fPath, sPath);
}
catch (Exception ee)
{
throw ee;
}
finally
{
myWebClient.Dispose();
}
return fName;
}
#endregion
}
}