Click here to Skip to main content
15,917,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 5 different text file inside the Main Folder example

c:\Main

inside Main, i have 5 file (test1.txt, test2.txt. test3.txt, test4.txt and test5.txt)

How to read the latest file?
Posted
Comments
Thomas Daniels 8-Apr-14 5:58am    
Is the file name always test5.txt or can the file also have another name?
KRI19 8-Apr-14 5:59am    
the file can have another name as well.
Thanks

Add check on Createdon by getting time like below:
C#
static void Main(string[] args)
       {
           DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");
           Console.WriteLine("file created: " + fileCreatedDate);
       }
 
Share this answer
 
Hi,
you can use
System.IO.File.GetCreationTime()

This methods gives the creation date and time of your file.
you can also specify an order or a creation date in your file name.
 
Share this answer
 
You need to list all files in a directory and check which was lastly writen.


Have a look here:
How to: Enumerate Directories and Files[^]
FileSystemInfo.LastWriteTime Property[^]
How to: Read From a Text File (C# Programming Guide)[^]
 
Share this answer
 
C#
public static string ReadLastFile(string dirPath)
{
    if (!Directory.Exists(dirPath))
      throw new FileNotFoundException();

    var lastFilePath = Directory.GetFiles(dirPath).OrderBy(f => new FileInfo(f).CreationTime).Last();
    return File.ReadAllText(lastFilePath);
}


You need to handle null states.
 
Share this answer
 
v2
Comments
KRI19 9-Apr-14 4:13am    
Thanks! worked fine

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900