C# 使用FileInfo类移动成对文件后,需要一种优雅的方法来从文件夹中移动孤立文件
我有一个文件夹,从中移动成对的相关文件(xml和pdf)。其他文件可以随时存放到此文件夹中,但该实用程序每10分钟左右运行一次。我们可以使用FileSystemWatcher类,但由于内部原因,我们不支持此实用程序 在每次运行期间,我使用System.IO.FileInfo类读取文件夹中的所有文件(仅为xml和pdf)。一旦我在FileInfo对象中有了这些文件,我就遍历这些文件,将匹配项移动到一个工作文件夹中。完成后,我想将任何未配对但位于FileInfo对象中的文件移动到故障文件夹 既然我似乎无法从FileInfo对象中删除项(或者我缺少了一些东西),那么(1)从Directory class.GetFiles中使用字符串数组,(2)从FileInfo对象中创建一个字典,并在迭代过程中删除其中的值,或者(3)是否有更优雅的方法使用LINQ或其他方法 以下是迄今为止的代码:C# 使用FileInfo类移动成对文件后,需要一种优雅的方法来从文件夹中移动孤立文件,c#,fileinfo,C#,Fileinfo,我有一个文件夹,从中移动成对的相关文件(xml和pdf)。其他文件可以随时存放到此文件夹中,但该实用程序每10分钟左右运行一次。我们可以使用FileSystemWatcher类,但由于内部原因,我们不支持此实用程序 在每次运行期间,我使用System.IO.FileInfo类读取文件夹中的所有文件(仅为xml和pdf)。一旦我在FileInfo对象中有了这些文件,我就遍历这些文件,将匹配项移动到一个工作文件夹中。完成后,我想将任何未配对但位于FileInfo对象中的文件移动到故障文件夹 既然我似
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;
}
老实说,我觉得这个问题有点糟糕。这个问题以一种非常复杂的方式陈述。我认为工作流的设计应该更加健壮和确定。(例如,为什么不首先上传压缩集的文件对?) (没有“某人”最有可能“以前一定没有来过这里”) 以下是一些随机改进:
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)
{
}
}
}
组来检测情况。其中(g=>g.Count()>2
)- 不要传递冗余参数。如果需要筛选,可以传递FI[]而不是raw GetFiles()调用
- 执行错误处理,特别是:
- 处理IO异常
- 上载过程中可能会出现锁定错误(测试它或最终导致文件损坏);您需要自动处理这些错误(即,除非可以移动所有文件,否则不要移动组中的任何文件;这将有点棘手)
- 测试您的代码(我的示例中没有一个经过测试;它只是在使用mono的linux上编译的)