简体   繁体   中英

How can I open the last file (.txt) that was created?

I have two programs, One create a .txt file when you click a button, and named those files with differences names like: "test1.txt , test2.txt , test3.txt ...etc." (The name of the files are not consecutive). The other program must open the file that was created last, and the only way to know which file was the last, is with "data modified" filter; because those file are created inside a specific folder (I use Windows 7 as Operating System). How can I open the last file that was created by the fist program?

Example:

test1.txt--- data modified: 08/03/2016 06:33am

test3.txt----data modified: 08/03/2016 06:35am

test4.txt----data modified: 08/03/2016 07:26am

test2.txt----data modified: 08/03/2016 09:35am I want open/read this file

I saw a lot of examples of the tool "FileSystemWatcher", but I really know how to compare the "data modified". Or exists another way to do that?

The simplest and most reliable way is to generate file names with time stamp in them. After, when you start reading them, parse the stamp and process all files in desired order.

Do not rely on system information about files , if that is feasible to your design, as it may miss-lead you on some machines (depends on Windows version, configuration...)

File.GetLastWriteTime seems to be returning 'out of date' value

    static void Main(string[] args)
    {
        var latestModifiedFile = GetLatestModifiedFile(@"Path here");
        Console.WriteLine(latestModifiedFile);
        System.Diagnostics.Process.Start(latestModifiedFile)
    }

    static string GetLatestModifiedFile(string directory)
    {
        var files = Directory.GetFiles(directory);
        return files.OrderBy(f => File.GetLastWriteTime(f)).LastOrDefault();
    }

And to answer your question about FileSystemWatcher:

    static void Main(string[] args)
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"Path here";
        watcher.NotifyFilter = NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "*.txt";
        watcher.Created += new FileSystemEventHandler(OnCreated);
        watcher.EnableRaisingEvents = true;

        Console.Read();
    }

    static void OnCreated(object source, FileSystemEventArgs e)
    {
        Console.WriteLine("Created file: " + e.FullPath);
        System.Diagnostics.Process.Start(e.FullPath);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM