簡體   English   中英

如何打開最后創建的文件(.txt)?

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

我有兩個程序,一個程序當您單擊一個按鈕時創建一個.txt文件,並將這些文件命名為不同的名稱,例如: "test1.txttest2.txttest3.txt ...等”。 (文件名不是連續的)。 另一個程序必須打開最后創建的文件,而知道哪個文件是最后一個的唯一方法是使用“數據已修改”過濾器。 因為這些文件是在特定文件夾內創建的(我使用Windows 7作為操作系統)。 如何打開由拳頭程序創建的最后一個文件?

例:

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 我想打開/讀取此文件

我看到了很多“ FileSystemWatcher”工具的示例,但我確實知道如何比較“修改后的數據”。 還是存在另一種方法?

最簡單,最可靠的方法是生成帶有時間戳的文件名。 之后,當您開始閱讀它們時,請分析圖章並按所需順序處理所有文件。

如果對您的設計可行,請不要依賴於文件的系統信息 ,因為這可能會導致您在某些計算機上誤導您(取決於Windows版本,配置...)

File.GetLastWriteTime似乎正在返回“過期”值

    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();
    }

並回答關於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);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM