如何对FileInfo []中的文件进行排序,然后将最后一个Gif文件从FileInfo []中的最后一个Gif文件分配给pictureBox1?

时间:2014-10-01 18:41:28

标签: c# .net winforms

path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
radarImagesDirectory = Path.Combine(path_exe, radarImagesDirectory);
dirinfo = new DirectoryInfo(radarImagesDirectory);
fileinfo = dirinfo.GetFiles("*.gif");
Bitmap bmp = new Bitmap(fileinfo[fileinfo.Length - 1].Name);
pictureBox1.Image = bmp;

在fileinfo中,我看到大约10000个文件的gif文件。 它们从0到10000开始,但它是真的排序吗?如果我将显示文件10000它是真的是最后一个文件还是需要一些如何对fileinfo进行排序?

我做了Bitmap bmp = new Bitmap(fileinfo [fileinfo.Length - 1] .Name);我想在pictureBox1中显示最后一个gif文件,但我在这一行得到例外:

参数无效

System.ArgumentException was unhandled
  HResult=-2147024809
  Message=Parameter is not valid.
  Source=System.Drawing
  StackTrace:
       at System.Drawing.Bitmap..ctor(String filename)
       at Weather_Radar.Form1..ctor() in d:\C-Sharp\Weather Radar\Weather Radar\Weather Radar\Form1.cs:line 47
       at Weather_Radar.Program.Main() in d:\C-Sharp\Weather Radar\Weather Radar\Weather Radar\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

1 个答案:

答案 0 :(得分:2)

这样的事可以帮助你:

var ordered = dirinfo.EnumerateFiles("*.gif")
                     .OrderByDescending(f => f.LastWriteTime);
FileInfo newest = ordered.FirstOrDefault();
FileInfo oldest = ordered.LastOrDefault();

Image img1 = Image.FromFile(newest.FullName);
// etc etc

(记住包括using System.Linq;