C#下载远程文件到本地

using System;
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 私有方法

        
/// <summary>
        
/// 随机返回文件名
        
/// </summary>
        
/// <returns></returns>
        private string getFileName()
        {
            System.Random objDom 
= new Random();
            
int intNum = objDom.Next(10009999);
            objDom 
= null;
            
string strNum = System.DateTime.Now.ToString("yyyyMMddhhmmss");
            
return strNum + intNum.ToString();
        }

        
/// <summary>
        
/// 根据文件得到文件扩展名
        
/// </summary>
        
/// <param name="fileName">文件名</param>
        
/// <returns></returns>
        private string getExtension(string fileName)
        { 
            
int start=fileName.IndexOf(".")+1;
            
string Ext = fileName.Substring(start, fileName.Length - start);
            
return Ext;
        }

        
#endregion

        
#region 公共方法

        
/// <summary>
        
/// 保存远程文件
        
/// </summary>
        
/// <param name="filePath">远程文件路径</param>
        
/// <returns></returns>
        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

    }
}

posted on 2009-07-30 15:40  韩显川  阅读(1679)  评论(0)    收藏  举报

导航