Skip to main content
 首页 » 编程设计

c#之使用正则表达式从 ListDirectoryDetails 中解析文件名

2024年04月17日37yyy_WW

我正在尝试解析来自 FileZilla FTP 服务器的 FTP ListDirectoryDe​​tails 响应。

主要问题是 FileZilla 服务器以不同的语言(文化)提供不同的输出。

我有两个来自 FileZilla 服务器的输出,都必须被解析,但我无法实现。

格式如下:

drwxr-xr-x 1 ftp ftp              0 Sep 02 17:07 Can 
-rw-r--r-- 1 ftp ftp              0 Jun 27 2016 Fan 
drwxr-xr-x 1 ftp ftp              0 Sep 21 12:29 AA AA 
-rw-r--r-- 1 ftp ftp             44 Sep 02 17:07 Debug.txt 

我尝试使用正则表达式来解决这个问题,但是编译失败。

我的正则表达式是:

(?<permissions>[drwx\-]+( (?<userandgroup>[A-Za-z]+ [A-Za-z]+) (?<size>\d+) (?<date>[A-Za-z]+ [\d:]+) (?<name> .*) 

我需要更健壮的正则表达式。也许只有文件名匹配正则表达式应该更好。

如何只匹配文件名与正则表达式?

请您参考如下方法:

要解析出文件名,只需获取第 9 个标记:

^(?:[^ ]+ +){8}(.*)$ 
Regex regex = new Regex("^(?:[^ ]+ +){8}(.*)$"); 
Match match = regex.Match(line); 
string filename = match.Groups[1].Value; 

尽管对于如此简单的解析,您实际上可以按空格将行拆分为标记。您不需要正则表达式。

string[] tokens = line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries); 
string filename = tokens[8]; 

但是如果您只需要一个文件名,请不要首先使用 ListDirectoryDe​​tails。使用 ListDirectory。它只返回文件名。


如果您需要解析文件属性,请使用支持 FTP MLSD 命令的 FTP 客户端。 FtpWebRequest 不支持这个。