var outputDirectory = new DirectoryInfo(@"G:\Local\Syndicationtest");
var sourceDirectory = new DirectoryInfo(@"G:\Local\Syndicationtest");
var sourceFiles = sourceDirectory.GetFiles();
foreach (var item in sourceFiles)
{
FileHelper.Copy(item, outputDirectory);
FileHelper.Move(FileHelper.Zip(item), new DirectoryInfo(@"G:\Local\Syndicationtest\History"));
}
我需要根据文件类型扩展名移动文件,换句话说源文件包含所有类型的扩展文件,我需要过滤以下“.xml”,“。dat”,“。txt”的文件类型, “.csv”,“。zip”,“。doc”并且只将这些文件移动到目标位置
答案 0 :(得分:2)
那怎么样:
var ext = new List<string> { ".xml", ".dat", ".txt", ".csv", ".zip", ".doc" };
var sourceFiles = sourceDirectory.GetFiles()
.Where(f => ext.Contains(f.Extension.ToLower()));
这解决了两件事:
DirectoryInfo.GetFiles(string searchPattern)
重载存在的三个字符扩展名问题。答案 1 :(得分:0)
使用Path.GetExtension()
您的代码:
var outputDirectory = new DirectoryInfo(@"G:\Local\Syndicationtest");
var sourceDirectory = new DirectoryInfo(@"G:\Local\Syndicationtest");
FileInfo[] sourceFiles = sourceDirectory.GetFiles();
var extensions = new List<string> { ".xml", ".dat", ".txt", ".csv", ".zip", ".doc" };
foreach (FileInfo item in sourceFiles)
{
if(extensions.Contains(item.Extension))
{
FileHelper.Copy(item, outputDirectory);
FileHelper.Move(FileHelper.Zip(item), new DirectoryInfo(@"G:\Local\Syndicationtest\History"));
}
}
如果你想使用LINQ,那么Michael Perrenoud的解决方案是首选。
答案 2 :(得分:0)
在这里你去..
您需要更改目录名称。
class Program
{
public static string outputDirecotry = @"C:DebugCopy";
public static void Main()
{
var fileExtenstions = new List<string>
{
".xml",
".dat",
".txt",
".csv",
".zip",
".doc"
};
foreach (var path in Directory.EnumerateFiles(@"C:Debug")
.Where(path => fileExtenstions.Contains(Path.GetExtension(path).ToLower())))
File.Copy(path , Path.Combine(outputDirecotry , Path.GetFileName(path)));
}
}
答案 3 :(得分:-2)
您可以在filePath中获取LastIndex
.
并阅读到最后获取扩展名。
然后您可以使用所需的扩展程序集进行验证。
试试这个:
var outputDirectory = new DirectoryInfo(@"G:\Local\Syndicationtest");
var sourceDirectory = new DirectoryInfo(@"G:\Local\Syndicationtest");
String[] FileExt = new String[] { ".xml", ".dat", ".txt", ".csv", ".zip", ".doc" };
var sourceFiles = sourceDirectory.GetFiles();
foreach (var item in sourceFiles)
{
if ((item.Contains(".")) && (FileExt.Contains(item.Substring(item.LastIndexOf("."), 4))))
{
FileHelper.Copy(item, outputDirectory);
FileHelper.Move(FileHelper.Zip(item), new DirectoryInfo(@"G:\Local\Syndicationtest\History"));
}
}