使用WinSCP .NET程序集对比本地远程文件时调用Except报错如何解决
问题原因
你调用Except失败的核心原因是待比对的两个集合类型完全不匹配:
list1是IEnumerable<RemoteFileInfo>类型,存储的是远程文件对象list2是IEnumerable<FileInfo>类型,存储的是本地文件对象
不同类型的集合无法直接用Except做差集运算,且你没有指定二者的比较规则,自然会触发类型不匹配报错。
解决方案
你可以先把两个集合投影为统一的可比较字段(比如文件相对路径、文件名+文件大小组合等),再做差集过滤,示例改造代码如下:
using System.Linq; // 首先确认已引入Linq命名空间 using (Session session = new Session()) { // Connect session.Open(sessionOptions); const string remotePath = "/Test"; const string localPath = @"C:\Local"; const string ArchivePath = @"C:\Users\Local\Archive"; System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(ArchivePath); // 提取本地所有文件的相对路径作为比对标识,存入HashSet提升查询效率 var localFileKeys = dir2.GetFiles("*.*", System.IO.SearchOption.AllDirectories) .Select(f => f.FullName.Substring(ArchivePath.Length).TrimStart('\\', '/')) .ToHashSet(); // 拉取所有远程csv文件 var remoteFiles = session.EnumerateRemoteFiles(remotePath, "*.csv", EnumerationOptions.None) .ToList(); // 过滤出本地不存在的远程新增文件 var newRemoteFiles = remoteFiles.Where(remoteFile => { // 把远程文件路径转成和本地规则一致的相对路径 var relativePath = remoteFile.FullName.Substring(remotePath.Length).TrimStart('\\', '/'); return !localFileKeys.Contains(relativePath); }).ToList(); // 后续遍历newRemoteFiles执行下载逻辑即可 }
如果需要避免同名不同内容的文件误判,可以把比对的key改成相对路径+文件大小+最后修改时间的组合字符串即可。
内容的提问来源于stack exchange,提问作者Nitz
相关产品推荐
相关产品推荐

