2015-12-02 22 views
0

我發現一個代碼非常有用,但下面的代碼從一個FTP服務器返回目錄和文件的名稱,我只需要獲取文件的名稱。FtpWebRequest只返回帶有ListDirectoryDe​​tails的文件名

ftpRequest = (FtpWebRequest) FtpWebRequest.Create(host + "/" + directory); 
/* Log in to the FTP Server with the User Name and Password Provided */ 
ftpRequest.Credentials = new NetworkCredential(user, pass); 
/* When in doubt, use these options */ 
ftpRequest.UseBinary = true; 
ftpRequest.UsePassive = true; 
ftpRequest.KeepAlive = true; 
/* Specify the Type of FTP Request */ 
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; 
/* Establish Return Communication with the FTP Server */ 
ftpResponse = (FtpWebResponse) ftpRequest.GetResponse(); 
/* Establish Return Communication with the FTP Server */ 
ftpStream = ftpResponse.GetResponseStream(); 
/* Get the FTP Server's Response Stream */ 
StreamReader ftpReader = new StreamReader(ftpStream); 
/* Store the Raw Response */ 
string directoryRaw = null; 
/* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */ 
try{ 
    while (ftpReader.Peek() != -1){ 
     directoryRaw += ftpReader.ReadLine() + "|"; 
    } 
} 
catch(Exception ex) 
{ 
     //Do something 
} 
... 
... 
... 

我調查,但WebRequestMethods.Ftp只有ListDirectoryListDirectoryDetails,都返回目錄和文件的名稱:(..

有人能幫助我..

感謝

+0

難道你不能只使用['Path.GetFileName'](https://msdn.microsoft.com/library/system.io.path.getfilename%28v=vs.110%29.aspx)? – cubrr

+0

哪裏?,在FTP?我認爲GetFileName是爲本地文件 – VhsPiceros

+0

嘗試'Path.GetFileName(「ftp://127.0.0.1/folder/filename.txt」)':o) – cubrr

回答

0

ListDirectory問題NLST命令僅返回文件名的服務器。

ListDirectoryDetails向服務器發出LIST命令,通常返回帶有詳細信息的文件名。

但它最終取決於服務器,它返回的內容。如果僅爲兩者返回文件名,那麼FtpWebRequest無法對此做任何事情。

服務器可能支持MLSD命令返回文件詳細信息,但FtpWebRequest不支持該功能。另一種替代方法是分別爲每個文件使用GetFileSizeGetDateTimestamp。但是這很慢。

另請參閱我的回答Retrieving creation date of file (FTP)

相關問題