根据searchPattern移动文件

我有excel列表,其中包含我想从一个文件夹移动到另一个文件夹的文件名。 而且我不能只将文件从一个文件夹粘贴到另一个文件夹,因为有些文件与excel列表不匹配。

private static void CopyPaste() { var pstFileFolder = "C:/Users/chnikos/Desktop/Test/"; //var searchPattern = "HelloWorld.docx"+"Test.docx"; string[] test = { "HelloWorld.docx", "Test.docx" }; var soruceFolder = "C:/Users/chnikos/Desktop/CopyTest/"; // Searches the directory for *.pst foreach (var file in Directory.GetFiles(pstFileFolder, test.ToString())) { // Exposes file information like Name var theFileInfo = new FileInfo(file); var destination = soruceFolder + theFileInfo.Name; File.Move(file, destination); } } } 

我已经尝试了几件事,但我仍然认为使用数组这将是最简单的方法(如果我错了,请纠正我)。

我现在面临的问题是它找不到任何文件(这个名称下有文件)。

您可以使用Directory.EnumerateFiles枚举目录中的文件,并使用linq表达式检查文件是否包含在您的字符串数组中。

 Directory.EnumerateFiles(pstFileFolder).Where (d => test.Contains(Path.GetFileName(d))); 

所以你的foreach会是这样的

 foreach (var file in Directory.EnumerateFiles(pstFileFolder).Where (d => test.Contains(Path.GetFileName(d))) { // Exposes file information like Name var theFileInfo = new FileInfo(file); var destination = soruceFolder + theFileInfo.Name; File.Move(file, destination); } 

实际上不,这不会在目录中搜索pst文件。 使用Path.Combine自己构建路径,然后遍历字符串数组,或使用您的方法。 使用上面的代码,您需要更新filter,因为在给定字符串[]。ToString()时它不会找到任何文件。 这应该做:

 Directory.GetFiles (pstFileFolder, "*.pst") 

或者,您可以在没有filter的情况下迭代所有文件,并将文件名与您的字符串数组进行比较。 为此, List将是一种更好的方法。 只需像你正在做的那样遍历文件,然后通过List.Contains检查List是否包含文件。

 foreach (var file in Directory.GetFiles (pstFileFolder)) { // Exposes file information like Name var theFileInfo = new FileInfo(file); // Here, either iterate over the string array or use a List if (!nameList.Contains (theFileInfo.Name)) continue; var destination = soruceFolder + theFileInfo.Name; File.Move(file, destination); } 

我想你需要这个

  var pstFileFolder = "C:/Users/chnikos/Desktop/Test/"; //var searchPattern = "HelloWorld.docx"+"Test.docx"; string[] test = { "HelloWorld.docx", "Test.docx" }; var soruceFolder = "C:/Users/chnikos/Desktop/CopyTest/"; // Searches the directory for *.pst foreach (var file in test) { // Exposes file information like Name var theFileInfo = new FileInfo(file); var source = Path.Combine(soruceFolder, theFileInfo.Name); var destination = Path.Combine(pstFileFolder, file); if (File.Exists(source)) File.Move(file, destination); }