我有一个文件夹,我从中移动成对的相关文件(xml 与 pdf 配对)。其他文件可以随时存入此文件夹,但该实用程序每 10 分钟左右运行一次。我们可以使用 FileSystemWatcher 类,但出于内部原因,我们不使用此实用程序。
我使用 System.IO.FileInfo 类在每次运行期间读取文件夹中的所有文件(只会是 xml 和 pdf)。在 FileInfo 对象中获得文件后,我会遍历文件,将匹配项移动到工作文件夹。完成后,我想将任何未配对但位于 FileInfo 对象中的文件移动到失败文件夹。
由于我似乎无法从 FileInfo 对象中删除项目(或者我遗漏了一些东西),(1)使用 Directory 类 .GetFiles 中的字符串数组,(2)从 FileInfo 对象创建一个 Dictionary 和在迭代期间从中删除值,或者(3)是否有使用 LINQ 或其他方法的更优雅的方法?
这是到目前为止的代码:
internal static bool CompareXMLandPDFFileNames(FileInfo[] xmlFiles, FileInfo[] pdfFiles, string xmlFilePath)
{
string workingFilePath = xmlFilePath + @"\WORKING";
if (xmlFiles.Length > 0)
{
foreach (var xmlFile in xmlFiles)
{
string xfn = xmlFile.Name; //xml file name
string pdfName = xfn.Substring(0,xfn.IndexOf('_')) + ".pdf"; //parsed pdf file name contained in xml file name
foreach (var pdfFile in pdfFiles)
{
string pfn = pdfFile.Name; //pdf file name
if (pfn == pdfName)
{
//move xml and pdf files to working folder...
FileInfo xmlInfo = new FileInfo(xmlFilePath + xfn);
FileInfo pdfInfo = new FileInfo(xmlFilePath + pfn);
if (!File.Exists(workingFilePath + xfn))
{
xmlInfo.MoveTo(workingFilePath + xfn);
}
if (!File.Exists(workingFilePath + pfn))
{
pdfInfo.MoveTo(workingFilePath + pfn);
}
}
}
}
//all files in the file objects should now be moved to working folder, if not, fix orphans...
}
return true;
}