CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 2005
    Posts
    3

    get most recently created file in a directory

    Hi-

    I'm not a C# programmer and I need to add some code to a project that determines the most recently created file in a directory.

    I'm not familiar with the .Net framework. I'm happy to work on syntax problems and any loops- but can someone sketch out what kinds of calls I should use?

    Thanks! Andy

  2. #2
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: get most recently created file in a directory

    I think this should work :

    Code:
    using System.IO;
    
    public class FileHelper
    {
        static public string GetMostRecentFile(string sFolderPath)
        {
            DateTime dateTime;
            bool fFirst = true;
            string sMostRecentFile = "";
        
            foreach (string sFile in Directory.GetFiles(sFolderPath))
            {
                if (fFirst)
                {
                    fFirst = false;
                    dateTime = File.GetCreationTime(Path.Combine(sFolderPath, sFile));
                    sMostRecentFile = sFile;
                }
                else
                {
                    DateTime dateTimeFile = File.GetCreationTime(Path.Combine(sFolderPath, sFile));
    
                    if (dateTimeFile > dateTime)
                    {
                        dateTime = dateTimeFile;
                        sMostRecentFile = sFile;
                    }
                }
            }
    
            return Path.Combine(sFolderPath, sMostRecentFile);
        }
    }
    If not, it should show you how to do it anyway.

    Darwen.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured