2015-12-02 33 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)