简体   繁体   English

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

[英]What could be the best way to get file path

I have 3 different directories where files are available for further processing. 我有3个不同的目录,这些文件可用于进一步处理。

  1. May be some directory not exist, hence I put try/catch . 可能是某些目录不存在,因此我放入了try/catch
  2. As soon as a single file available in any directory, I am returning the path. 只要在任何目录中都有一个文件,我就会返回路径。

Here is below code, question, what could be the best way to get file path as above functionality? 这是下面的代码,有问题,用上述功能获取文件路径的最佳方法是什么?

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

You could use Directory.Exists instead: 您可以改用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;
}

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

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