『壹』 C++程序中如何實現ftp多線程下載
本人不才,下面這個是從網路上轉來的.不知可有幫助.
這是codeproject的關於ftp的實現,你可以去down源代碼
Introction
StuffFTP is a free for life FTP client. This FTP client will allow you to connect to FTP servers and upload and download files.
Motivation
Why did I create and continue to support StuffFTP? First it is a learning experience, and since I just got laid off from my company, I decided to use some of the tools they have provided, its legal as I technically bought them and they do not have other programmers following in my footstep nor do they plan on hiring any, to create something for the community. I also used another FTP program that was freeware for a while and then became pay to use software with little to no notice. That irked me and a friend suggested I create my own FTP client. So I am.
Progress
This is currently a work in progress and I would be the first to say there is a lot of work to do. Since I am laid off, I have lots of time on my hands. And this is an excellent chance for me to learn some of the concepts of C++ that I wanted to, but never had the chance while I was working. I was hoping to get a job in San Jose, CA, but decided to hold off and live on saving for a while.
Guarantee
I will support this program as best as I can. I have already setup a website and forum for it, here. I use the forum because I have trouble responding to email especially when I get a whole bunch of SPAM everyday. There is no adware or spyware in the program, and I guarantee that it will be free for the life of the program.
Some people have already asked why I don't open source the project. The main reason is I do not know if I can. StuffFTP uses some proprietary third party libraries. I do not know if I can post the source code or header files to those libraries. So everyone will have to wait until I can get rid of those libraries or hear back from the companies concerning my question about releasing header and associated help files.
Tools
* MS Windows XP Professional
* MS Visual Studio .NET C++/MFC
* Clickteam Install Maker
* Clickteam Patch Maker
* Betaone.net forum members
* CXListCtrl by Hans Dietrich
3rd Party Libraries
The application uses Catalyst Socket Tools Library Edition and Professional UI GUI library. So far the support has been fair with Prof-UI and outstanding with Catalyst. The Catalyst tool is for the actual FTP connection and, as the name suggests, Prof-UI is being used for the GUI.
Updates
You can find the latest updates here and you can also find my latest ramblings, blogs, and support here. This is where you can find out all the latest versions and information.
How to contribute
Money! Just kidding you can contribute by downloading, using, and giving feedback on the program. That way I can determine which path to take with the application and which features to prioritize or not. Graphics is also where I need lots of help. I am left brained and can not draw a good stick figure to save my life. If you can help with graphics or anything else, please let me know. Also talk to me, I am bored. I have no job at the moment so I can use the company.
Features
* Able to upload/download from server/computer
* Connect to FTP sites using login
* Connect using other ports besides 21
* Delete, rename, and CHMOD a file
History
* 12/10/2003 - Version 0.11a
* 12/07/2003 - Version 0.10a
『貳』 C#通過FTP下載文件夾
第一部分是實現單個文件下載的方法
///<summary>
///單個文件下載方法
///</summary>
///<paramname="adss">保存文件的本地路徑</param>
///<paramname="ftpadss">下載文件的FTP路徑</param>
publicvoiddownload(stringadss,stringftpadss)
{
//FileMode常數確定如何打開或創建文件,指定操作系統應創建新文件。
//FileMode.Create如果文件已存在,它將被改寫
FileStreamoutputStream=newFileStream(adss,FileMode.Create);
FtpWebRequestdownRequest=(FtpWebRequest)WebRequest.Create(newUri(ftpadss));
//設置要發送到FTP伺服器的命令
downRequest.Method=WebRequestMethods.Ftp.DownloadFile;
FtpWebResponseresponse=(FtpWebResponse)downRequest.GetResponse();
StreamftpStream=response.GetResponseStream();
longcl=response.ContentLength;
intbufferSize=2048;
intreadCount;
byte[]buffer=newbyte[bufferSize];
readCount=ftpStream.Read(buffer,0,bufferSize);
while(readCount>0)
{
outputStream.Write(buffer,0,readCount);
readCount=ftpStream.Read(buffer,0,bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
第二個部分也就是需要遍歷出所指定的文件夾內所有內容
首先是一個單個遍歷文件夾獲取文件夾下所有文件信息的方法
///</summary>
///<paramname="ftpads">FTP地址路徑</param>
///<paramname="name">我們所選擇的文件或者文件夾名字</param>
///<paramname="type">要發送到FTP伺服器的命令</param>
///<returns></returns>
publicstring[]ftp(stringftpads,stringname,stringtype)
{
WebResponsewebresp=null;
StreamReaderftpFileListReader=null;
FtpWebRequestftpRequest=null;
try
{
ftpRequest=(FtpWebRequest)WebRequest.Create(newUri(ftpads+name));
ftpRequest.Method=type;
webresp=ftpRequest.GetResponse();
ftpFileListReader=newStreamReader(webresp.GetResponseStream(),Encoding.Default);
}
catch(Exceptionex)
{
ex.ToString();
}
StringBuilderstr=newStringBuilder();
stringline=ftpFileListReader.ReadLine();
while(line!=null)
{
str.Append(line);
str.Append("/n");
line=ftpFileListReader.ReadLine();
}
string[]fen=str.ToString().Split('/n');
returnfen;
}
之後是一個我們實現遞歸文件夾的方法
///<summary>
///下載方法KO
///</summary>
///<paramname="ftpads">FTP路徑</param>
///<paramname="name">需要下載文件路徑</param>
///<paramname="Myads">保存的本地路徑</param>
publicvoiddownftp(stringftpads,stringname,stringMyads)
{
stringdownloadDir=Myads+name;
stringftpdir=ftpads+name;
string[]fullname=ftp(ftpads,name,WebRequestMethods.Ftp.ListDirectoryDetails);
//判斷是否為單個文件
if(fullname.Length<=2)
{
if(fullname[fullname.Length-1]=="")
{
download(downloadDir+"/"+name,ftpads+name+"/"+name);
}
}
else
{
string[]onlyname=ftp(ftpads,name,WebRequestMethods.Ftp.ListDirectory);
if(!Directory.Exists(downloadDir))
{
Directory.CreateDirectory(downloadDir);
}
foreach(stringnamesinfullname)
{
//判斷是否具有文件夾標識<DIR>
if(names.Contains("<DIR>"))
{
stringolname=names.Split(newstring[]{"<DIR>"},
StringSplitOptions.None)[1].Trim();
downftp(ftpdir,"//"+olname,downloadDir);
}
else
{
foreach(stringonlynamesinonlyname)
{
if(onlynames==""||onlynames==""||names=="")
{
break;
}
else
{
if(names.Contains(""+onlynames))
{
download(downloadDir+"/"+onlynames,ftpads+name+"/"+
onlynames);
break;
}
}
}
}
}
}
}
在使用WebRequestMethods.Ftp.ListDirectoryDetails取得文件夾下所有內容時,會發現如果其中有文件夾,那麼文件夾的的詳細信息中會有一個"<DIR>"標識,我們就可以通過這個來將其區分開來
同時在獲取文件夾以及文件名稱時用到WebRequestMethods.Ftp.ListDirectory,這個指令能過只獲得文件夾下所有文件包括文件夾的名字,通過這兩個指令所獲取的信息逐一比較,便能確定出文件或文件夾名以傳遞到download和downftp方法中
『叄』 C語言實現從FTP下載、上傳文件
FTP 是File Transfer Protocol(文件傳輸協議)的英文簡稱,而中文簡稱為「文傳協議」。
1.C語言可以使用CStdioFile函數打開本地文件。使用類CInternetSession 創建並初始化一個Internet打開FTP伺服器文件。
CStdioFile繼承自CFile,一個CStdioFile 對象代表一個用運行時函數fopen 打開的C 運行時流式文件。
流式文件是被緩沖的,而且可以以文本方式(預設)或二進制方式打開。文本方式提供對硬回車—換行符對的特殊處理。當你將一個換行符(0x0A)寫入一個文本方式的CStdioFile 對象時,位元組對(0x0D,0x0A)被發送給該文件。當你讀一個文件時,位元組對(0x0D,0x0A)被翻譯為一個位元組(0x0A)。
CStdioFile 不支持Duplicate,LockRange,和UnlockRange 這幾個CFile 函數。如果在CStdioFile 中調用了這幾個函數,將會出現CNoSupported 異常。
使用類CInternetSession 創建並初始化一個或多個同時的Internet 會話。如果需要,還可描述與代理伺服器的連接。
如果Internet連接必須在應用過程中保持著,可創建一個類CWinApp的CInternetSession成員。一旦已建立起Internet 會話,就可調用OpenURL。CInternetSession會通過調用全局函數AfxParseURL來為分析映射URL。無論協議類型如何,CInternetSession 解釋URL並管理它。它可處理由URL資源「file://」標志的本地文件的請求。如果傳給它的名字是本地文件,OpenURL 將返回一個指向CStdioFile對象的指針。
如果使用OpenURL在Internet伺服器上打開一個URL,你可從此處讀取信息。如果要執行定位在伺服器上的指定的服務(例如,HTTP,FTP或Gopher)行為,必須與此伺服器建立適當的連接。
『肆』 使用visual c++怎樣實現ftp伺服器的上傳和下載急----
你用用C++的開源庫POCO,
只要下面的簡單代碼就可以實現FTP。。
#include "Poco/Net/FTPClientSession.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/NetException.h"
。。。
using Poco::Net::FTPClientSession;
using Poco::Net::SocketAddress;
using Poco::Net::FTPException;
。。。
FTPClientSession session(host, port);//創建FTP會話對象
session.login(username, password); //登錄
session.setWorkingDirectory(path); //轉到工作目錄
ostream& os= session.beginUpload(fileName);//指定遠尺差程文陵察皮件名開始上傳
os << "test" ; //上傳內容
session.endUpload(); //結束沒世上傳
『伍』 怎麼從FTP上下載東西
其實我建議使用一個專門的ftp客戶端來使用ftp比較好,這樣你只需要在客戶端上輸入ftp伺服器的IP和埠,賬號,密碼,就能輕松的上傳和下載文件,非常實用。
這里我推薦使用IIS7伺服器管理工具,它可以作為FTP的客戶端,想要進行FTP的上傳下載操作,只需要下載安裝iis7伺服器管理工具就可以了!免費下載,很方便。
同時它還可以作為VNC的客戶端,進行VNC的相應操作!它能夠連接Windows和Linux系統下的伺服器和VPS,能滿足你不同系統的使用,感覺不錯的話可以試試
『陸』 在MFC ftp下載文件的程序中 怎樣使用Getfile()下載文件,在遠程路徑中使用的是URL地址 還是其他什麼
請注意第一個參數不支持路徑,只支持文件名。下載某個子目錄下的文件,需要先用SetCurrentDirectory()進入該文件夾。
『柒』 c# 從ftp下載文件到本地指定位置
我就給了個1.exe的下載,其它的做尺此循環可以解決
FTP下載衫困陸
/*
using System.IO;
private Stream stream = null;
private StreamReader reader = null;
private FileInfo f= null;
private StreamWriter writer = null;
private char[] c =null;
*/
f = new FileInfo(@"D:\Temp\1.exe");
if(f.Exists() && MessageBox.show("文件已或頃存在,是否重新下載?", "打、打、打劫",MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)==DialogResult.Cancel)
return;
try
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://.com/2010/1.exe");
ftpRequest.Credentials = new NetworkCredential("user", "user");
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
stream = ftpResponse.GetResponseStream();
reader = new StreamReader(stream, Encoding.Default);
writer = f.CreateText();
while (reader.Peek() >= 0)
{
//This is an arbitrary size for this example.
char[] c = new char[5120];
reader.Read(c, 0, c.Length);
writer.Write(c);
}
writer.Flush();
}
catch
{
return "讀取FTP文件失敗";
}
finally
{
if (reader != null) { reader.Close(); }
if (stream != null) { stream.Close(); }
if (writer != null) { writer.Close(); }
}
『捌』 從ftp伺服器上下載文件
[code]?php
/**
* 函數名 php_ftp_download
* 功能 從Ftp服務族則器上下載文件
* 入口參數
* filename 欲下載的文件名,含路徑
*/
function php_ftp_download($filename) {
$phpftp_host = "ftplocalhost"; // 伺服器地兆核棚址
$phpftp_port = 21; // 伺服器埠
$phpftp_user = "name"; // 用戶名
$phpftp_passwd = "passwrd"; // 口令
$ftp_path = dirname($filename) . "/"; // 獲取路徑
$select_file = basename($filename); // 獲取文件名
$ftp = ftp_connect($phpftp_host,$phpftp_port); // 連接Ftp伺服器
if($ftp) {
if(ftp_login($ftp, $phpftp_user, $phpftp_passwd)) { // 登錄
if(@ftp_chdir($ftp,$ftp_path)) { // 進入指定路徑
$tmpfile = tempnam( getcwd()."/", "temp" ); // 創建唯一的臨時文件
if(ftp_get($ftp, $tmpfile, $select_file, FTP_BINARY)) { // 下載指定的文件到臨氏悉時文件
ftp_quit( $ftp ); // 關閉連接
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . $select_file);
readfile($tmpfile);
unlink($tmpfile ); // 刪除臨時文件
exit;
}
unlink($tmpfile );
}
}
}
ftp_quit($ftp);
}
?
[/code][button value="復制代碼"]
『玖』 寫個小程序從FTP上下載文件
從indy clients組件面板中拖一個idftp組件, 然後在按鈕中寫如下代碼 idftp1.host := '192.168.0.1'; //ftp伺服器的ip地址 idftp1.username := '***'; //登錄ftp伺服器的用戶名 idftp1.password := '***'; //登錄ftp伺服器的密碼 idftp1.port := '21'; //埠號默認為21,如果不更改則不加此行代碼 if IdFTP1.Connected then IdFTP1.Disconnect; begin try IdFTP1.Connect(); except showmessage('FTP鏈接失敗!'); exit; end; end; //開始上傳 idftp1.put('需上傳文件的目錄名','需上傳文件的文件名',false); //開始下載 idftp1.get('ftp伺服器目錄','存放本地目錄名',如果文件存在是否覆蓋已存在文件,是否重命名文件名);
『拾』 C#從ftp下載文件如何判斷下載結束
從流里讀取的位元組數為0時,則下載結束。
c#實現絕如 ftp ;http;共享方式下載文件 並對比本地文件和伺服器文件的更新時間 判斷性下載
//從ftp伺服器上下載文件的功能
public void Download(string ftpServerIP, string ftpUserID, string ftpPassword, string fileName, string Destination)
{
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(Destination + "\\" + fileName, FileMode.Create);
// 根據uri創建FtpWebRequest對象行手
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
// 指定執行什麼命令
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
// 默認為true,連接不會被關閉
reqFTP.UseBinary = true;
// ftp用戶名和密碼
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse ftpresponse = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = ftpresponse.GetResponseStream();
long cl = ftpresponse.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
ftpresponse.Close();
}
catch (Exception ex)
{
}
}
//從http伺服器上下載文件的功能
//為服務並帶啟器路徑server_path
//本地存儲路徑local_path
public void Download(string server_path, string local_path)
{
HttpWebRequest req;
try
{
string folder = local_path.Substring(0, local_path.LastIndexOf("\\"));
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
// 根據uri創建FtpWebRequest對象
req = (HttpWebRequest)HttpWebRequest.Create(new Uri(server_path));
// 指定執行什麼命令
req.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
if (File.Exists(local_path))
{
FileInfo localFile = new FileInfo(local_path);
if (localFile.LastWriteTime > response.LastModified) return;
}
FileStream outputStream = new FileStream(local_path, FileMode.Create);
Stream stream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = stream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = stream.Read(buffer, 0, bufferSize);
}
stream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
string s = ex.Message;
}
}
//從共享文件夾下載
public void Download(string server_path, string local_path, int i)
{
try
{
server_path = "\\" + server_path;
string folder = local_path.Substring(0, local_path.LastIndexOf("\\"));
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
if (!File.Exists(server_path)) return;
//伺服器文件信息
FileInfo serverInfo = new FileInfo(server_path);
DateTime serverTime = serverInfo.LastWriteTime;
if (File.Exists(local_path))
{
FileInfo localinfo = new FileInfo(local_path);
DateTime localTime = localinfo.LastWriteTime;
if (localTime >= serverTime)
return;
}
serverInfo.CopyTo(local_path, true);
return;
}
catch (Exception ex)
{
string s = ex.Message;
}
}