我面临一个奇怪的问题,我想从FTP下载文件列表。我更喜欢使用Parallel Task。以下是我的代码。问题是,所有文件列表都已下载,但正在生成具有不同名称的重复文件。我对Parallel任务概念很新。请帮我找出问题所在。
注意:我使用SSH.Net进行sftp连接和下载。
private void ConcurrentDownload()
{
// Declaring Connection Information
PasswordAuthenticationMethod pm = new PasswordAuthenticationMethod("FTPUserName", "Password");
ConnectionInfo connectionInfo = new ConnectionInfo("FTPHost", 22, "FTPUserName", ProxyTypes.Socks5, "127.0.0.1", 8080, string.Empty, string.Empty, pm);
using (SftpClient sfc = new SftpClient(connectionInfo))
{
// Establish the remote connection
sfc.Connect();
// Getting Remote Directory Contents
IEnumerable<SftpFile> sFiles = new List<SftpFile>();
sFiles = sfc.ListDirectory(".\\");
// Building the File List
List<string> remotefiles = new List<string>();
foreach (SftpFile sfile in sFiles)
{
if (!sfile.IsDirectory)
{
string ss = sfile.Name;
remotefiles.Add(ss);
}
}
// Parallel Download
Parallel.ForEach(remotefiles.Distinct(), file => DownloadFile(sfc, file));
sfc.Disconnect();
}
}
private void DownloadFile(SftpClient sf, string RemoteFileName)
{
using (Stream ms = File.OpenWrite(RemoteFileName))
{
sf.DownloadFile(RemoteFileName, ms);
}
}
答案 0 :(得分:0)
您最好使用Distinct
,如下所示
Parallel.ForEach(remotefiles.Distinct(), file => DownloadFile(sfc, file));
如果您有重复的文件名,并且在同一文件上启动并行处理时,您将在这些重复文件上获得异常。
而且您也没有下载到其他位置,您正在做的是下载到相同的ftp源位置。那是对的吗?
我会提供不同的下载目录并从源文件中获取文件名,然后下载到该位置,如下所示
private void DownloadFile(SftpClient sf, string RemoteFileName)
{
string downloadTo = Path.Combine(DownloadDirectoryPath, Path.GetFileName(RemoteFileName));
using (Stream ms = File.OpenWrite(downloadTo))
{
sf.DownloadFile(RemoteFileName, ms);
}
}