我有一个C#脚本,目前正在两个目录之间移动文件。它一次移动10个文件。问题是它是按文件名抓取10个文件。我希望它每次运行时都能获取最早的10个文件。我怎么能这样做?
目前,我的脚本如下所示:
string[] dirsSourceDirectory = System.IO.Directory.GetDirectories(sourceDirectory);
string[] filesSourceDirectory = System.IO.Directory.GetFiles(sourceDirectory);
string[] dirsDestinationDirectory = System.IO.Directory.GetDirectories(destinationDirectory);
string[] filesDestinationDirectory = System.IO.Directory.GetFiles(destinationDirectory);
int filecount = Directory.GetFiles(destinationDirectory, "*.TRN", SearchOption.TopDirectoryOnly).Length;
for (int i = 1; i <= 10; i++)
{
FileInfo[] rgfiles = di.GetFiles();
rgfiles[0].MoveTo(System.IO.Path.Combine(destinationDirectory, rgfiles[0].Name));
}
谢谢!
答案 0 :(得分:5)
var filesToMove = di
.GetFiles()
.OrderBy(f => f.CreationTime)
.Take(10)
.ToArray();
foreach (var rgFile in filesToMove)
{
rgfile.MoveTo(System.IO.Path.Combine(destinationDirectory, rgfile.Name));
}
答案 1 :(得分:1)
使用LINQ获取从最旧到最新排序的文件数组,如下所示:
var fileInfoArray = di.GetFiles().OrderBy(fi => fi.CreationTime).Take(10).ToArray();
然后你可以遍历文件:
foreach(var file in fileInfoArray)
{
file.MoveTo(System.IO.Path.Combine(destinationDirectory, file.Name));
}
答案 2 :(得分:0)
您只需使用CreationTime功能:http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime.aspx
答案 3 :(得分:0)
尝试一些linq
List<string> slist = Directory.GetFiles(@"c:\temp").OrderBy(fn => File.GetCreationTime(fn)).ToList();