打开最近的txt文件

时间:2012-08-22 06:53:29

标签: c# file-io

有点麻烦我试图让最新的txt文件打开。 我正在使用一个按钮,我需要在一个catch中打开txt文件 事情是有几百个文本文件,我需要按日期和时间的最后一个文件

// ..............更新............. //

这是我的文件外观的更好示例 有一些额外的日志,他们内容更新

commandlog2012081410   (2012-08-14 /  01:01)
commandlog2012081411   (2012-08-14 /  10:30)
commandlog2012081412   (2012-08-14 /  12:36)
Sample2012082207   (2012-08-22   /  02:12)
Sample2012082208   (2012-08-22   /  06:28)
Sample2012082209   (2012-08-22   /  09:14)
faillog2012075671   (2012-07-17  /  01:20)
faillog2012075672   (2012-07-17  /  08:00)
faillog2012075673   (2012-07-17  /  09:00)
chargedlog203416771   (2012-07-05 /  20:36)
chargedlog203416772   (2012-07-05 /  21:20)
chargedlog203416773   (2012-07-05 /  22:42)
vanishlog2012324795   (2012-07-21 / 17:00)
vanishlog2012324796   (2012-07-21 / 19:31)
vanishlog2012324797   (2012-07-21 / 20:28)
debuglog123131231    (2012-08-22 / 05:10)
debuglog123131232    (2012-08-22 / 06:12)
debuglog123131233    (2012-08-22 / 09:14)
droplogg12313131    (2012-08-06 / 10:10)
droplogg12313132    (2012-08-06 / 16:41)
exitlog123131313     (2012-08-22  /   01:01)
exitlog123131314     (2012-08-22  /   01:12)
exitlog123131315     (2012-08-22  /   09:14)
log201123131     (2012-08-22  / 09:12)
log201123132     (2012-08-22  / 09:14)

我需要打开// Sample2012082209(2012-08-22 / 09:14)// 正如你可以看到一些其他txt文件在同一天同时结束,甚至可以选择那个文件并打开它

        catch (Exception ex)
        {
            MessageBox.Show("Error" + ex.Message.ToString());
         (Open newest Sample txt file here)
        }

2 个答案:

答案 0 :(得分:3)

您可以使用Linq和File.GetLastAccessTime Method获取最后一个openend文件:

var openedFiles = from fName in Directory.EnumerateFiles(dir, "*.txt")
                 orderby File.GetLastAccessTime(fName) descending
                 select new FileInfo(fName);
if (openedFiles.Any())
{
    var lastOpenedFile = openedFiles.First();
}

Directory.EnumerateFiles(dir, "*.txt")仅返回txt - 给定目录中的文件。

编辑:我担心这个问题仍然不明确,即使你已经编辑过,你也写过几条评论。但是,如果您只想要以给定名称开头的文件(f.e. “Sample”),则必须调整EnumerateFiles的搜索模式:

var name = "Sample";
var openedFiles = from fName in Directory.EnumerateFiles(dir, name + "*.txt")
                  orderby File.GetLastAccessTime(fName) descending
                  select new FileInfo(fName);

答案 1 :(得分:0)

您可以使用DirectoryInfo类获取有关给定目录的信息。从那里你可以获得文件,并使用FileInfo类获取有关创建日期之类的信息。这是一个例子:

    DirectoryInfo dirInfo = new DirectoryInfo(@"C:\");
    foreach (FileInfo file in dirInfo.GetFiles())
    {
        DateTime creationdate = file.CreationTime;
    }

如果您需要更多信息,请发表评论

相关问题