我有一个文件夹,我要从其中移动成对的相关文件(成对的xml和pdf)。可以随时将其他文件存放到此文件夹中,但该实用程序大约每10分钟运行一次。我们可以使用FileSystemWatcher类,但由于内部原因,我们不能使用此实用程序。
在每次运行期间,我使用System.IO.FileInfo类来读取文件夹中的所有文件(将只是xml和pdf)。将文件放入FileInfo对象后,我将遍历这些文件,将匹配项移动到一个工作文件夹中。完成此操作后,我希望将所有未配对但位于FileInfo对象中的文件移动到失败文件夹中。
既然我似乎不能从FileInfo对象中删除条目(或者我遗漏了什么),那么(1)使用目录类.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;
}发布于 2011-03-23 10:05:57
老实说,我认为这个问题有点糟糕。这个问题是以一种非常复杂的方式陈述的。我认为工作流程应该设计得更健壮,更具确定性。(例如,为什么不首先在压缩集中上传文件对?)
(而且没有“某人”最有可能“以前肯定没有来过这里”)
以下是一些随机的改进:
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
namespace O
{
static class X
{
private static readonly Regex _xml2pdf = new Regex("(_.*).xml$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
internal static void MoveFileGroups(string uploadFolder)
{
string workingFilePath = Path.Combine(uploadFolder, "PROGRESS");
var groups = new DirectoryInfo(uploadFolder)
.GetFiles()
.GroupBy(fi => _xml2pdf.Replace(fi.Name, ".pdf"), StringComparer.InvariantCultureIgnoreCase)
.Where(group => group.Count() >1);
foreach (var group in groups)
{
if (!group.Any(fi => File.Exists(Path.Combine(workingFilePath, fi.Name))))
foreach (var file in group)
file.MoveTo(Path.Combine(workingFilePath, file.Name));
}
}
public static void Main(string[]args)
{
}
}
}groups.Where(g => g.Count()>2)不再检测到该组
其他项目(待办事项)
的linux上编译的
https://stackoverflow.com/questions/5399171
复制相似问题