简体   繁体   English

如何在C#中仅使用System.IO命名空间中的GetFiles获取目录中最新创建的文件

[英]how to get the newest created file in a directory using only GetFiles in System.IO Namespace in C#

I would like to create a method which returns me the newest created file in a Directory in C# with the preferred usage of the Directory.GetFiles() method in the System.IO Namespace.我想创建一个方法,该方法返回 C# 目录中最新创建的文件,并首选使用 System.IO 命名空间中的 Directory.GetFiles() 方法。 Maybe it's possible to do it also without LINQ to keep it compatible with NET 2.0.也许在没有 LINQ 的情况下也可以做到这一点,以使其与 NET 2.0 兼容。 Good would be also if the FilePath could be returned as a string not as a File Object if possible The construct should look like below, but how I can see the newest file only?如果可能的话,FilePath 可以作为字符串返回而不是作为文件对象返回也很好构造应该如下所示,但我如何才能看到最新的文件?

public static string NewestFileofDirectory(string DirectoryName)
{
 foreach(string File in Directory.GetFiles(DirectoryName))
 {
  if(new FileInfo(File).CreationDate > ???) //here I stuck
  {
    //interesting what would be here...
  }
 }
}

Boilerplate search coming right up.样板搜索马上就来了。 Thank god for LINQ :)感谢上帝的 LINQ :)

var minTime = DateTime.MinValue;

string theFile = null;

foreach (var entry in Directory.GetFiles(dirName))
{
    if (File.GetCreationTimeUtc(entry) > minTime)
    {
        minTime = File.GetCreationTimeUtc(entry);
        theFile = entry;
    }
}

You can do this using theFileInfo and DirectoryInfo classes.您可以使用FileInfoDirectoryInfo类来执行此操作。 You will first get all the files in the specified directory and then compare their LastWriteTime to others and thus by comparison you can get the most recently writte or recent file.您将首先获取指定目录中的所有文件,然后将它们的LastWriteTime与其他文件进行比较,从而通过比较您可以获得最近写入或最近的文件。 Here is code for this method.这是此方法的代码。

 /// <summary>
 /// Returns recently written File from the specified directory.
 /// If the directory does not exist or doesn't contain any file, null is returned.
 /// </summary>
 /// <param name="directoryInfo">Path of the directory that needs to be scanned</param>
 /// <returns></returns>
 public static string NewestFileofDirectory(string directoryPath )
 {
    DirectoryInfo directoryInfo  = new DirectoryInfo(directoryPath);
    if (directoryInfo == null || !directoryInfo.Exists)
        return null;

     FileInfo[] files = directoryInfo.GetFiles();
     DateTime recentWrite = DateTime.MinValue;
     FileInfo recentFile = null;

     foreach (FileInfo file in files)
     {
         if (file.LastWriteTime > recentWrite)
         {
            recentWrite = file.LastWriteTime;
            recentFile = file;
         }
      }
         return recentFile.Name;
 }

Both of the above answers have issues with empty directories.以上两个答案都存在空目录问题。 Here is a hybrid answer that checks for empty dir and non existent dir.这是一个检查空目录和不存在目录的混合答案。

    /// <summary>
    /// Returns most recently written Filename from the specified directory.
    /// If the directory does not exist or doesn't contain any file, null is returned.
    /// </summary>
    /// <param name="directoryInfo">Path of the directory that needs to be scanned</param>
    /// <param name="filePattern">Search Pattern for file</param>
    /// <returns></returns>
    public static string NewestFileInDirectory(string directoryPath, string filePattern)
    {
        DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
        if (directoryInfo == null || !directoryInfo.Exists)
        {
            return null;
        }

        var minTime = DateTime.MinValue;

        string newestFile = null;

        foreach (var file in Directory.GetFiles(directoryPath, filePattern))
        {
            var fileLastWriteTime = File.GetLastWriteTimeUtc(file);
            if (fileLastWriteTime > minTime)
            {
                minTime = fileLastWriteTime;
                newestFile = file;
            }
        }
        return newestFile;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 System.IO 在 c# 中将文件转换为数组 - Convert a File to Array in c# using System.IO System.IO中没有“目录”或“文件” - No “Directory” or “File” in System.IO C#使用System.IO,System.Data和CSVReader根据文件和传输文件的邮政编码值创建目录 - C# Create Directory based on ZIP code value of file and Transfer Files using System.IO, System.Data, & CSVReader System.IO.Directory.GetFiles()是否无法检索C#中的任何文件? - System.IO.Directory.GetFiles() not retrieving any files in C#? c#使用system.io保存标签; - c# saving tabs using system.io; 使用 System.IO 复制 C# 中的文件夹 - Copy Folders in C# using System.IO 视觉 C# 错误:命名空间“System.IO”中不存在类型或命名空间名称“Compression” - Visual C# Error: The type or namespace name 'Compression' does not exist in the namespace 'System.IO' C# Streamreader“找不到类型或命名空间名称”错误,但我有 System.IO 命名空间 - C# Streamreader "The type or namespace name could not be found" error, but I've got the System.IO namespace 无法使用 C# 中的 System.Io 检索文件的作者信息 - Unable to retrieve the Author's information of a file using System.Io in C# C# System.IO 如何获取我的项目中文件夹的路径 - C# System.IO How to get path to a folder in my project
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM