获取文件路径的最佳方法是什么

用户584018

我有 3 个不同的目录,其中的文件可用于进一步处理。

  1. 可能是某个目录不存在,因此我把try/catch.
  2. 只要在任何目录中有单个文件可用,我就会返回路径。

这是下面的代码,问题是,获取上述功能的文件路径的最佳方法是什么?

private static string GetRealPath()
    {
        const string filePath1 = @"C:\temp1\";
        const string filePath2 = @"C:\temp2\";
        const string filePath3 = @"C:\temp\";

        //looks for file in  @"C:\temp1\ 
        try
        {
            if (Directory.EnumerateFileSystemEntries(filePath1, "*.txt").ToList().Count > 0)
            {
                return filePath1;
            }
        }
        catch (Exception e) { Console.WriteLine(e); }

        //looks for file in  @"C:\temp2\ 
        try
        {
            if (Directory.EnumerateFileSystemEntries(filePath2, "*.txt").ToList().Count > 0)
            {
                return filePath2;
            }
        }
        catch (Exception e) { Console.WriteLine(e); }

        //looks for file in  @"C:\temp\ 
        try
        {
            if (Directory.EnumerateFileSystemEntries(filePath3, "*.txt").ToList().Count > 0)
            {
                return filePath3;
            }
        }
        catch (Exception e) { Console.WriteLine(e); }

        return string.Empty;
    }
蒂姆·施梅尔特

你可以Directory.Exists改用:

public static string GetFirstValidPath()
{
    string[] paths = { @"C:\temp1\", @"C:\temp2\", @"C:\temp\"};
    return paths.FirstOrDefault(p=> Directory.Exists(p) 
       && Directory.EnumerateFileSystemEntries(p, "*.txt").Any()) ?? string.Empty;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在运行时获取可执行文件路径的最佳方法是什么?

从 Scala 中的 Spark 获取位于 GCS 存储桶中的所有文件的路径的最佳方法是什么?

从 .eml 文件中获取文本的最佳方法是什么?

给定相对路径,从集群中获取ActorRef的最佳方法是什么?

获取未运行的应用程序的完整路径的最佳方法是什么?

获取文件子路径的最佳方法

解决不存在文件的相对路径(如realpath)的最佳方法是什么?

从对象获取实体的最佳方法是什么?

linux +合并文件的最佳方法是什么

从文件加载脚本的最佳方法是什么?

组织功能文件的最佳方法是什么?

从ESModules中的复杂路径导入模块的最佳方法是什么

在Restkit中纠缠路径模式的最佳方法是什么

确定两个文件路径引用同一文件对象的最佳方法是什么?

通过Microsoft Graph的路径来获取SharePoint文件的最简单方法是什么?

XmlReader获取当前文件路径的方法名称是什么?

针对XSD文件验证XML文件的最佳方法是什么?

分割文件后再次加入文件的最佳方法是什么?

快速创建多个文件的.cab文件的最佳方法是什么?

将地图的值作为向量获取的最佳方法是什么?

在Clojure中获取日期和时间的最佳方法是什么?

JPA 获取摘要对象的最佳方法是什么?

在Angular 4 Dart中获取ComponentFactory的最佳方法是什么?

获取迭代器的计数/长度/大小的最佳方法是什么?

在 RxJS 中修补获取的对象的最佳方法是什么?

从存储的多个片中获取NGRX数据的最佳方法是什么

获取 JSON 字符串值的最佳方法是什么?

从UITableView获取“拉动刷新”的最佳方法是什么?

使用CsvHelper获取列名列表的最佳方法是什么?