,我讀了FTP文件/文件夾列表。檢查是否是文件或文件夾上的FTP
問題是,我不知道,如果是文件或文件夾。 目前我正在檢查字符串是否有擴展名。如果是,則是文件,否則爲文件夾。但是,這還不夠好,它可以存在的文件沒有擴展名和文件夾的擴展名(例如,文件夾名稱可能是FolderName.TXT。)
這是代碼,我用它來列出文件夾的內容:
public async Task<CollectionResult<string>> ListFolder(string path)
{
try
{
FtpWebRequest ftpRequest = null;
var fileNames = new List<string>();
var res = new CollectionResult<string>();
ftpRequest = ftpBuilder.Create(path, WebRequestMethods.Ftp.ListDirectory);
using (var ftpResponse = (FtpWebResponse)await ftpRequest.GetResponseAsync())
using (var ftpStream = ftpResponse.GetResponseStream())
using (var streamReader = new StreamReader(ftpStream, Encoding.UTF8))
{
string fileName = streamReader.ReadLine();
while (!string.IsNullOrEmpty(fileName))
{
fileNames.Add(Path.Combine(path, fileName.Substring(fileName.IndexOf('/') + 1, fileName.Length - fileName.IndexOf('/') - 1)));
fileName = streamReader.ReadLine();
}
}
ftpRequest = null;
res.ListResult = fileNames;
return res;
}
catch (Exception e)
{
e.AddExceptionParameter(this, nameof(path), path);
throw;
}
}
如果我能夠在while循環中檢測到文件或文件夾是最好的,但是不可能僅從字符串中進行此操作。
謝謝你的幫助。
編輯
我發現類似的問題。 C# FTP, how to check if a Path is a File or a Directory? 但問題是很老,也沒有很好的解決方案。
編輯:解
public async Task<CollectionResult<Tuple<string, bool>>> ListFolder(string path)
{
try
{
FtpWebRequest ftpRequest = null;
var fileNames = new CollectionResult<Tuple<string, bool>>();
fileNames.ListResult = new List<Tuple<string, bool>>();
if (!(IsFtpDirectoryExist(path)))
{
throw new RemoteManagerWarningException(ErrorKey.LIST_DIRECTORY_ERROR, fileNames.ErrorMessage = $"path folder {path} not exists");
}
ftpRequest = ftpBuilder.Create(path, WebRequestMethods.Ftp.ListDirectoryDetails);
using (var ftpResponse = (FtpWebResponse)await ftpRequest.GetResponseAsync())
using (var ftpStream = ftpResponse.GetResponseStream())
using (var streamReader = new StreamReader(ftpStream, Encoding.UTF8))
{
while (!streamReader.EndOfStream)
{
string line = streamReader.ReadLine();
string[] tokens = line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
// is number:
Regex rgx = new Regex(@"^[\d\.]+$");
var isExternalFtpOrUnixDirectoryStyle = !(rgx.IsMatch(line[0].ToString()));
string name = string.Empty;
bool isFolder = false;
if (isExternalFtpOrUnixDirectoryStyle)
{
name = tokens[8];
var permissions = tokens[0];
isFolder = permissions[0] == 'd';
}
else
{
tokens = line.Split(new[] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries);
name = tokens[3];
isFolder = tokens[2] == "<DIR>";
}
name = Path.Combine(path, name);
Tuple<string, bool> tuple = new Tuple<string, bool>(name, isFolder);
fileNames.ListResult.Add(tuple);
}
}
ftpRequest = null;
return fileNames;
}
catch (Exception e)
{
e.AddExceptionParameter(this, nameof(path), path);
throw;
}
}