#region 下載文件 /// <summary> /// 從FTP服務器下載文件,指定本地路徑和本地文件名,20120817,ylh /// </summary> /// <param name="ftpPath">要下載文件所在ftp上的完整路徑,如ftp://192.168.0.111/2012-08-17/yinluhui.xml</param> /// <param name="ftpFile">要下載文件的文件名,如yinluhui.xml</param> /// <param name="LocalPath">本地路徑,如D:\ftp臨時文件\20120817</param> public bool DownFtpToLocation(String ftpPath, String ftpFile, String LocalPath) { byte[] bt = null; try { //if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(LocalFileName) || !IsValidPathChars(LocalPath)) //{ // throw new Exception("非法文件名或目錄名!"); //} if (Directory.Exists(LocalPath) == false) { Directory.CreateDirectory(LocalPath); } string LocalFullPath = Path.Combine(LocalPath, ftpFile); //if (File.Exists(LocalFullPath)) //{ // throw new Exception("當前路徑下已經存在同名文件!"); //} bt = DownloadFile(ftpPath, LocalPath); if (bt != null) { FileStream stream = new FileStream(LocalFullPath, FileMode.Create); stream.Write(bt, 0, bt.Length); stream.Flush(); stream.Close(); return true; } else { return false; } } catch (Exception ep) { //ErrorMsg = ep.ToString(); throw ep; } } /// <summary> /// 從FTP服務器下載文件,返回文件二進制數據 /// </summary> public byte[] DownloadFile(String ftpPath, String LocalPath) { try { //if (!IsValidFileChars(RemoteFileName)) //{ // throw new Exception("非法文件名或目錄名!"); //} FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpPath); ftpRequest.Credentials = new NetworkCredential(_account, _pwd);//登陸ftp的用戶名,密碼 ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; FtpWebResponse Response = (FtpWebResponse)ftpRequest.GetResponse(); Stream Reader = Response.GetResponseStream(); MemoryStream mem = new MemoryStream(1024 * 500); byte[] buffer = new byte[1024]; int bytesRead = 0; int TotalByteRead = 0; while (true) { bytesRead = Reader.Read(buffer, 0, buffer.Length); TotalByteRead += bytesRead; if (bytesRead == 0) break; mem.Write(buffer, 0, bytesRead); } if (mem.Length > 0) { return mem.ToArray(); } else { return null; } } catch (Exception ep) { throw ep; } } #endregion